pg14-sql基础(三)-分组

分组

SELECT hire_date, COUNT(*)
FROM employees
GROUP BY hire_date;

pg14-sql基础(三)-分组_第1张图片

SELECT extract(year from hire_date), COUNT(*)
FROM employees
GROUP BY extract(year from hire_date);
-- GROUP BY 1;

pg14-sql基础(三)-分组_第2张图片

SELECT extract(year from hire_date), department_id, COUNT(*)
FROM employees
GROUP BY 1,2;

pg14-sql基础(三)-分组_第3张图片

SELECT department_id, COUNT(*)
FROM employees
GROUP BY department_id
HAVING COUNT(*)>10;
-- 对分组后的数据进行二次统计用having,不能用where

pg14-sql基础(三)-分组_第4张图片

高级分组

测试数据

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)
*/

pg14-sql基础(三)-分组_第5张图片

--美化
SELECT coalesce(item, '所有产品') AS "产品", coalesce(year, '所有年份') AS "年份", SUM(quantity)
FROM sales
GROUP BY ROLLUP (item, year);

pg14-sql基础(三)-分组_第6张图片

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)
*/

pg14-sql基础(三)-分组_第7张图片

SELECT coalesce(item, '所有产品') AS "产品", coalesce(year, '所有年份') AS "年份", SUM(quantity)
FROM sales
GROUP BY GROUPING SETS ((year), (item), ());
/*
GROUPING SETS用于自定义组和,ROLLUP、CUBE是其特殊项 
*/

pg14-sql基础(三)-分组_第8张图片

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)就是以二进制数值表示是多字段的汇总
*/

pg14-sql基础(三)-分组_第9张图片

你可能感兴趣的:(pg-sql,sql,分组统计)