GROUP BY语句将具有相同值的行分组到汇总行中
GROUP BY语句通常与聚合函数(COUNT,MAX,MIN,SUM,AVG)一起使用,将结果集分组为一列或多列。
SQL GROUP BY 语法
SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s) ORDER BY column_name(s);
-- 按照title 分组:
select title from employee group by title;
-- 统计按照title分组,每组数据多少:
SELECT COUNT(title) AS "分组统计" FROM employee GROUP BY title;
-- distinct筛选去重与group by分组有相同之处:
SELECT DISTINCT(title) FROM employee;
-- 分组升序排列:
SELECT last_name FROM employee GROUP BY last_name ORDER BY last_name;
-- 分组降序排列:
SELECT last_name FROM employee GROUP BY last_name ORDER BY last_name DESC;
-- 分组查询不同的值的数据:
SELECT COUNT(DISTINCT salary) FROM employee GROUP BY salary;
-- 查询分组数据数:
SELECT salary, COUNT(*)FROM employee GROUP BY salary ORDER BY salary;
-- 按照分组数据升序 / 降序排列:
-- 升序
SELECT salary, COUNT(*)FROM employee GROUP BY salary ORDER BY COUNT(salary);
-- 降序
SELECT salary, COUNT(*)FROM employee GROUP BY salary ORDER BY COUNT(salary) DESC;