postgres —— 分组集

Posted lemos

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了postgres —— 分组集相关的知识,希望对你有一定的参考价值。

创建表

create table t_oil (
    region text,
    country text,
    year   text,
    production int,
    comsumption int
)

 

导入数据

copy t_oil from program ‘curl https://cybertec-postgresql.com/secret/oil_ext.txt‘;

 

分组集的应用

-- region,country 4 + region 2 + 1
SELECT region, country, avg(production) from t_oil where country in (‘USA‘, ‘Canada‘, ‘Iran‘, ‘Oman‘) 
group by  rollup (region, country);

-- region,country 4 + region 2 + country 4 + 1
SELECT region, country, avg(production) from t_oil where country in (‘USA‘, ‘Canada‘, ‘Iran‘, ‘Oman‘) 
group by  cube (region, country);

-- same above
SELECT region, country, avg(production) from t_oil where country in (‘USA‘, ‘Canada‘, ‘Iran‘, ‘Oman‘) 
group by GROUPING SETS ((), region, country, (region, country));

 

部分聚集 filter

SELECT region, avg(production) as all,
avg(production) FILTER (where year < 1990) as old,
avg(production) FILTER (where year >= 1990) as new
from t_oil 
group by rollup(region);

  

233

以上是关于postgres —— 分组集的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Postgres 的窗口函数中获取 mode()?

Postgres 按值更改分区/分组

postgres 按聚合函数分组

如何按postgres数组中的多个ID分组

简单的更新集 postgres 存储过程

在 Postgres 中分组为 2 小时的间隔