postgresql grouping

group summary

aggregate function

An aggregate function operates on a set of rows and returns a single result. PostgreSQL
supports the following common aggregate functions:

AVG - Calculates the average of a set of values.
COUNT - counts the number of values ​​in a set.
MAX - Calculates the maximum value of a set of values.
MIN - Calculates the minimum of a set of values.
SUM - Calculates the sum of a set of values.
STRING_AGG - concatenates a group of strings.

-- 部门所有员工的平均薪水、员工总数、最高薪水、最低薪水、以及薪水总计
-- 聚合函数忽略NULL数据行,count(*)除外
-- 聚合函数中的distinct会对数据去重
SELECT AVG(salary),
 COUNT(distinct manager_id),
 MAX(salary),
 MIN(salary),
 SUM(salary)
 FROM employees;

insert image description here

-- 字符串的聚合
SELECT string_agg(first_name,';' order by first_name)
 FROM employees;

insert image description here

Notice

  • Add the DISTINCT keyword before the function parameter to exclude duplicate values ​​during calculation.
  • ignore NULL values ​​in parameters

Summarize

insert image description here

Group Statistics

-- 分组统计
-- extract 提取
-- extract(year from hire_date) 统计入职日期按年
SELECT extract(year from hire_date) as years,count(*)
 FROM employees
 group by  extract(year from hire_date);
 -- 上述sql可以简写为如下sql
 -- group by 1表示按照查询的第一列分组
 SELECT extract(year from hire_date) as years,count(*)
 FROM employees
 group by 1;
 -- 统计每年每个部门有多少人入职
 SELECT extract(year from hire_date) as years,department_id,count(*)
 FROM employees
 group by 1,2;

Summarize

insert image description here

advanced grouping

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',1800);
-- rollup向上翻滚
select item,year,sum(quantity)
from sales
group by rollup(item,year);
-- rollup相当于group by item,year+group by item+sum(quantity)
-- rollup按照层级进行分组
-- coalesce去除非空字段
select coalesce(item,'所有产品') as "产品",coalesce(year,'所有年份')as "年份",sum(quantity)
from sales
group by rollup(item,year);

insert image description here

Summarize

insert image description here

Guess you like

Origin blog.csdn.net/Java_Fly1/article/details/132352931
Recommended