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

水223

这是我在select语句中的sql示例。从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不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
      . . .
     ) . . .

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何重写 COUNT DISTINCT?

如何在Distinct ON上使用count

如何编写COUNT(DISTINCT())查询?

PostgreSQL中的SUM COUNT DISTINCT

GROUP BY 中 DISTINCT 的 Elasticsearch COUNT

COUNT(DISTINCT)在PostgreSQL中如何工作

PySpark的csv文件上的distinct()。count()

在$ query中添加COUNT和DISTINCT

访问查询中的Count(Distinct FieldName)

如何在MySQL中获取DISTINCT列和COUNT列?

APPROX_COUNT_DISTINCT 如何工作以提供比 Oracle 中的 count 函数更好的性能?

Spark:如何在Dataframe API的中转换count(distinct(value))

如何在MySQL中使用Between子句加速count(distinct)

如何使用DISTINCT和COUNT创建MySQL嵌套查询

如何使SQL请求COUNT DISTINCT有条件?

来自Power BI中多个表的COUNT DISTINCT值

核心数据中的SELECT COUNT(DISTINCT ZUSER)

合并两个表中的distinct和count()

MS Access 中每个 ID 的 SQL COUNT DISTINCT

如何获取 DISTINCT 列和子 DISTINCT 列的 COUNT 次出现

如何在SQL Server中一起使用count,case和Distinct

如何在一个值之前的值上计算集合函数COUNT(DISTINCT)?

如何使用EF Core在转换后的SQL中获得COUNT DISTINCT

使用 COUNT (DISTINCT..) 同时使用 INNER JOIN 连接 3 个表但 Postgres 不断出错

將 SUM 組添加到 COUNT DISTINCT 查詢中

在Power BI中创建一个按国家和品牌返回DISTINCT COUNT的度量

Spark函数中的roxenCountDsitinct和roximate_count_distinct之间的差异

SELECT COUNT(*)DISTINCT-查找表中任何重复组的总出现次数

MySQL COUNT DISTINCT