【问题标题】:How to implement Oracle count(distinct) over partition in Postgres如何在 Postgres 中通过分区实现 Oracle 计数(不同)
【发布时间】:2017-04-19 21:32:02
【问题描述】:

这是我在 select 语句中的 sql 示例。从 oracle 转换为 postgres,需要一种简单的方法来在 postgres 中重新实现 oracle count distinct over partition。

, 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

【问题讨论】:

  • 我认为您不能在 Oracle 或 Postgres 的窗口函数中使用 distinct
  • 目前在 oracle 中工作。为 postgres 寻找解决方法。

标签: sql oracle postgresql


【解决方案1】:

Postgres 不直接支持count(distinct)。但是您可以使用子查询来实现它:

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
      . . .
     ) . . .

这个想法很简单。在 partition by 键和不同的列上计算 row_number()。然后,只需将值为“1”时的次数相加。这需要一个子查询,因为您不能嵌套窗口函数。

【讨论】:

  • 最终实现了这个版本。谢谢。
猜你喜欢
  • 2019-04-30
  • 2017-12-31
  • 1970-01-01
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
  • 2020-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多