postgres —— 有序集与假象聚集

有序集

--  有序集。分组后,按给定顺序排序,再进行计算
SELECT region, percentile_disc(0.5) WITHIN GROUP (order by production) from 
t_oil group by region;

-- 中位数函数
-- percentile_disc 找相似值; percentile_cont 找精确值,没有则插入
SELECT percentile_disc(0.62) WITHIN GROUP (order by id),
percentile_cont(0.62) WITHIN group (order by id)
from generate_series(1,5) as id;

-- 查找最频繁的值
SELECT production, count(*)
from t_oil
where country = 'Other Middle East'
group by production
order by 2 desc
limit 4;

-- 3 个不同的值出现了正好5次。当然,mode 函数只能给出其中一个
SELECT country, mode() WITHIN GROUP (order by production)
from t_oil
where country = 'Other Middle East'
group by 1;

假象聚集

-- 假象函数, 用以解决如果一个值在其中将会怎样的问题。
-- 类似于有序集。使用 rank 函数, 如果某地区日产 9000桶,那将是北美地区第27好的年份以及中东地区第21好的年份
SELECT region, rank(9000) WITHIN GROUP
(order by production desc nulls last)
from t_oil
group by rollup(1)

  

PS:测试数据在上一篇

233

猜你喜欢

转载自www.cnblogs.com/lemos/p/12052222.html