1.概述
分组,所谓的分组就是将一个“数据集”划分成若干个“小区域”,然后针对若干个“小区域”进行数据处理。
2.原始表
3.简单GroupBy
可以看出,通过 type 分组后,num 和 remark 数量不是唯一的,结果里面 num 和 remark 对应的值都是取的同一 type 最后一条记录的对应值。
4.GroupBy 和 OrderBy
SELECT
type,remark,
SUM(num) AS total
FROM
test
GROUP BY
type
ORDER BY
total DESC
这里的结果和原始数据表的数据不太对号,是因为期间数据表有过更改。
5.Where + GroupBy
注意必须在 GroupBy 之前指定 Where 子句。
SELECT type, SUM(num) AS total, remark FROM test
WHERE num > 10
GROUP BY type
6.GroupBy + Having
HAVING子句可包含一个或多个用AND和OR连接的谓词。
SELECT type, SUM(num) AS total, remark FROM test
GROUP BY type
HAVING total > 10
SELECT type, SUM(num) AS total, remark FROM test
GROUP BY type
HAVING total > 10
AND total < 100