postgresql 視窗函式排序例項

2021-09-06 21:10:59 字數 1835 閱讀 7096

經常遇到一種應用場景,將部分行的內容進行彙總、比較、排序。

比如資料表名稱test.test2

select num,province from test.test2

得到結果:

1828;"

黑龍江"

137;"

黑龍江"

184;"

黑龍江"

183;"福建"

125;"福建"

143;"福建"

119;"海南"

109;"海南"

132;"

海南"

那麼我希望將內容按照省份來排序,那麼需要:

select

province,

num,

sum(num) over (partition by province order

by num desc rows between unbounded preceding and

current row) as

all_num

from test.test2

得到結果:

"海南";132;132

"海南";

119;251

"海南";

109;360

"福建";

183;183

"福建";

143;326

"福建";

125;451

"黑龍江";

1828;1828

"黑龍江";

184;2012

"黑龍江";

137;2149

如果還要看每行佔整個省份的百分比,那麼需要

with tmp as

(select

province,

num,

sum(num) over (partition by province order

by num desc rows between unbounded preceding and

current row) as

curr_num,

sum(num) over (partition by province rows between unbounded preceding and unbounded following) as

all_num

from

test.test2

)select

province,

num,

all_num,

curr_num

/all_num

from tmp

結果如下

"海南";132;360;0.36666666666666666667

"海南";

119;360;0.69722222222222222222

"海南";

109;360;1.00000000000000000000

"福建";

183;451;0.40576496674057649667

"福建";

143;451;0.72283813747228381375

"福建";

125;451;1.00000000000000000000

"黑龍江";

1828;2149;0.85062819916240111680

"黑龍江";

184;2149;0.93624941833410888785

"黑龍江";

137;2149;1.00000000000000000000

postgreSQL常用函式

select coalesce sum duration 0 若sum duration 返回值為空,則為其賦值0 select to date 2013 12 20 yyyy mm dd 字串轉化為date型別 select date 2013 10 28 01 00 interval 50 mi...

postgresql 內建函式

一 算術函式 數值計算 1,2,abs 絕對值 abs 數值 3,mod 求餘 mod 被除數,除數 4,round 四捨五入 round 物件數值,保留小數的位數 二 字串函式 字串操作 1,拼接 select str1,str2 str1 str2 as str concat from 表名 2...

postgresql常用函式

create table search.t test 20200108 c id varchar 300 c field varchar 300 insert into search.t test 20200108 values 1 醫療器械類,化妝品類,藥品類,食品類 concat ws第乙個引數...