postgres —— 窗口函数入门 postgres —— 分组集与部分聚集

注:测试数据在 postgres —— 分组集与部分聚集 中

聚集将多行转变成较少、聚集的行。而窗口则不同,它把当前行与分组中的所有行对比,并且返回的行数没有变化。

组合当前行与 production 的均值

SELECT country, year, production,comsumption, 
avg(production) over() 
from t_oil;

  

分组

组合当前行与 按年份分组后,当前行所在分组的 production 的均值

SELECT country, year, production,comsumption, 
avg(production) over(partition by year) 
from t_oil;

  

组合当前行与 按年份>2000 分组后,当前行所在分组的 production 的均值

SELECT country, year, production,comsumption, 
avg(production) over(partition by year > 2000) 
from t_oil;

  

排序

组合当前行与 按年份排序后, 到当前行为止 的 最小 production

SELECT country, year, production, 
min(production) over (partition by country order by year)
from t_oil
where year between 1978 and 1983
and country in ('Iran', 'Oman')

  

 注:可以看到,随着行数增加,最小值一直在改变。比如,到第5行为止时,最小值为 1321。

233

猜你喜欢

转载自www.cnblogs.com/lemos/p/12057611.html
今日推荐