postgresl中的width_bucket 函數
一、場景訴求
場景一:
需要對學科成績進行等級劃分。A[100-85]、B(85~70]、C(70-60]、D(60-0] 進行一個劃分。
- 想知道每個人分數對應的等級
- 想知道 獲取A成績的有多少人、B等級的有多少人,C等級的有多少人。
- 想知道 A 、B 、C 、D的佔比
場景二:
根據每個終端的銷量,給每個終端打標籤。
場景三: 生成空間熱力圖
echart
官網案例地址:https://echarts.baidu.com/examples/#chart-type-heatmap
這樣的場景還有很多,需要設計到劃分等級的,都可以將其歸於這個場景。
二、場景實現
2.1 成績等級劃分
-- width_bucket 分數應用
create table student(
snum int PRIMARY key, -- 學號
int, -- 學科
score int -- 分數
);
INSERT INTO student(snum,subject,score)
SELECT t.id, 1,round(random()*100)
FROM generate_series(1,10000,1)t(id);
-- 成績、佔比、總數
select
case lev
when 4 then 'A'
when 3 then 'B'
when 2 then 'C'
ELSE 'D' END AS grade,
levcount, round(100*(levcount/(sum(levcount) over ())), 2)||' %' as ratio
from(
select width_bucket(score, array[0,60,70,85]) as lev, count(*) as levcount
from student where subject=1 group by 1
) t order by lev desc;
知識補充: 使用
group by 1
等進行排序的好處在於不用擔心排序字段不在表中
其他案例
參考
- PostgreSQL 9.6.0 手冊 http://www.postgres.cn/docs/9.6/functions-math.html