简体   繁体   English

如何在Postgres中的分区上实现Oracle count(distinct)

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

Here is my sql sample in a select statement. 这是我在select语句中的sql示例。 Converting from oracle to postgres, need a simple way to re implement oracle count distinct over partition in postgres. 从oracle转换为postgres,需要一种简单的方法来重新实现与postgres中的分区不同的oracle计数。

, 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. Postgres不直接支持count(distinct) 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. partition by键和不同的列计算partition by上的row_number() Then, just add up the number of times when the value is "1". 然后,只需将值等于“ 1”的次数相加即可。 This requires a subquery, because you cannot nest window functions. 这需要一个子查询,因为您不能嵌套窗口函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM