一、常用聚合函數
1.
函數 | 意義 |
---|---|
sum() | 總合 |
avg() | 平均 |
max() | 最大值 |
min() | 最小值 |
count()計數 | 意義 |
---|---|
count(student) | 記錄學生的個數null值不計數 |
count(1) | 計算索引數量 |
count(*) | 計算所有數據數量 |
二、案例:分組過濾查詢.
查詢不同課程的學生的成績的平均分,最高分,最低分,平均分要大於60分,
核心通過不同的課程進行分組,( WHERE 不能和 GROUP BY 連用,使用 HAVING 代替)
1. 建表.
1.建表
CREATE TABLE `studentexam` (
`name` varchar(100) DEFAULT NULL COMMENT '學生姓名',
`testSubject` varchar(20) DEFAULT NULL COMMENT '考試科目',
`score` varchar(2) DEFAULT NULL COMMENT '分數等級',
`numberScore` int(11) DEFAULT NULL COMMENT '分數數字'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
2.插入數據後:(你也可以隨機插入數據)
2. 查詢
(1)第一次嘗試。
SELECT
`studentexam`.`testSubject` AS 科目,
AVG(`studentexam`.`numberScore`)AS 平均分,
MAX(`studentexam`.`numberScore`) AS 最高分,
MIN(`studentexam`.`numberScore`) AS 最低分
FROM `studentexam`
效果:
結論:只有數學一門課,這是因爲沒有分組的緣故。(2)我們是用group by 分組
(2)第二次嘗試,使用group by 分組,
SELECT
`studentexam`.`testSubject` AS 科目,
AVG(`studentexam`.`numberScore`)AS 平均分,
MAX(`studentexam`.`numberScore`) AS 最高分,
MIN(`studentexam`.`numberScore`) AS 最低分
FROM `studentexam`
GROUP BY 科目
效果:
結論:分組成功,下面我們新的要求查詢平均分及格的以上條件。
(3)在(2) 的基礎查詢平均分及格的科目,
SELECT
`studentexam`.`testSubject` AS 科目,
AVG(`studentexam`.`numberScore`)AS 平均分,
MAX(`studentexam`.`numberScore`) AS 最高分,
MIN(`studentexam`.`numberScore`) AS 最低分
FROM `studentexam`
WHERE `studentexam`.`numberScore` >= 60
GROUP BY 科目
效果:報錯
where 的地方錯了.
原因是where不能和 group by 連用,使用 having 代替.(4)
(4) 在(3)的基礎上使用 having 替代 where (注意select 語法)
(重點)select 語法
select
[all|distanct] -- 1.字段
from
[table1|table1,table2] -- 2.表
inner join [table_2] ---3.聯合查詢
on [聯合查詢條件] --
where... -- 3.where 滿足條件
group by [...] -- 4.分組
having [...] -- 分組的次要條件
order by [表.字段 desc|ASC] -- 5.排序
limit [開始查詢的行數],[查詢的行數];
-- 6.分頁.
having 在 group by 的後面.
SELECT
`studentexam`.`testSubject` AS 科目,
AVG(`studentexam`.`numberScore`)AS 平均分,
MAX(`studentexam`.`numberScore`) AS 最高分,
MIN(`studentexam`.`numberScore`) AS 最低分
FROM `studentexam`
GROUP BY 科目
HAVING 平均分 > 60
效果:
結論:查詢成功,having 在 group by 的後面,使用group by 分組》