postgresql 視窗函數

來源:互聯網
上載者:User

標籤:

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

比如資料表名稱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_numfrom 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_numfrom test.test2)select    province,   num,  all_num,  curr_num/all_numfrom 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 視窗函數

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.