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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.