How to implement Oracle count(distinct) over partition in Postgres

大兔子大兔子 提交于 2021-01-27 22:38:27

问题


Here is my sql sample in a select statement. Converting from oracle to postgres, need a simple way to re implement oracle count distinct over partition in postgres.

, count(distinct on pm.mobseg_state) over (partition by pm.trans_id) as mob_segments_count  
, count(distinct on pm.country_reg_region_cd) over (partition by pm.trans_id) as countries_count

回答1:


Postgres doesn't support count(distinct) directly. But you can implement it with a subquery:

select . . .,
       sum( (seqnum_tm = 1)::int) as mob_segments_count ,
       sum( (seqnum_tr = 1)::int) as countries_count
from (select . . .,
             row_number() over (partition by pm.trans_id, pm.country_reg_region_cd order by pm.country_reg_region_cd) as seqnum_tr,
             row_number() over (partition by pm.trans_id, pm.mobseg_state order by pm.pm.mobseg_state) as seqnum_tm
      . . .
     ) . . .

The idea is simple. Calculate row_number() on the partition by keys and the distinct column. Then, just add up the number of times when the value is "1". This requires a subquery, because you cannot nest window functions.



来源:https://stackoverflow.com/questions/43506443/how-to-implement-oracle-countdistinct-over-partition-in-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!