分组
SELECT hire_date, COUNT(*)
FROM employees
GROUP BY hire_date;
SELECT extract(year from hire_date), COUNT(*)
FROM employees
GROUP BY extract(year from hire_date);
-- GROUP BY 1;
SELECT extract(year from hire_date), department_id, COUNT(*)
FROM employees
GROUP BY 1,2;
SELECT department_id, COUNT(*)
FROM employees
GROUP BY department_id
HAVING COUNT(*)>10;
-- 对分组后的数据进行二次统计用having,不能用where
高级分组
测试数据
CREATE TABLE sales (
item VARCHAR(10),
year VARCHAR(4),
quantity INT
);
INSERT INTO sales VALUES('apple', '2018', 800);
INSERT INTO sales VALUES('apple', '2018', 1000);
INSERT INTO sales VALUES('banana', '2018', 500);
INSERT INTO sales VALUES('banana', '2018', 600);
INSERT INTO sales VALUES('apple', '2019', 1200);
INSERT INTO sales VALUES('banana', '2019', 180
SELECT item, year, SUM(quantity)
FROM sales
GROUP BY ROLLUP (item, year);
/*
相当于GROUP BY item, year和GROUP BY item, SUM(quantity)和SUM(quantity)
*/
--美化
SELECT coalesce(item, '所有产品') AS "产品", coalesce(year, '所有年份') AS "年份", SUM(quantity)
FROM sales
GROUP BY ROLLUP (item, year);
SELECT coalesce(item, '所有产品') AS "产品", coalesce(year, '所有年份') AS "年份", SUM(quantity)
FROM sales
GROUP BY CUBE (item, year);
/*
相当于GROUP BY (item, year)和GROUP BY (item)和GROUP BY (year)和SUM(quantity)
*/
SELECT coalesce(item, '所有产品') AS "产品", coalesce(year, '所有年份') AS "年份", SUM(quantity)
FROM sales
GROUP BY GROUPING SETS ((year), (item), ());
/*
GROUPING SETS用于自定义组和,ROLLUP、CUBE是其特殊项
*/
SELECT coalesce(item, '所有产品') AS "产品", coalesce(year, '所有年份') AS "年份", SUM(quantity),
GROUPING(item), GROUPING(year), GROUPING(item,year)
FROM sales
GROUP BY GROUPING SETS ((year), (item), ());
/*
倒数2、3列的GROUPING表示是前面哪一列的汇总,在没有使用coalesce()时方便查看
最后一列的GROUPING(item,year)就是以二进制数值表示是多字段的汇总
*/