问题
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