PostgreSQL:计算多列中的唯一值

问题描述 投票:0回答:1

让我们有一个包含两列 [col1, col2] 和一些值的表。 col1 和 col2 中的值可以重复。我想从两列中获取唯一值的数量。

select
   count(distinct col1) as col1_unique,
   count(distinct col2) as col2_unique,
   count(distinct (col1, col2)) as total_unique
from myTable

返回total_unique作为col1、col2的组合,它总是大于col1_unique和col2_unique的总和

例如: 带行的表:

1 1
1 2
1 3
2 1
2 2
2 2

应返回 col1_unique 为 2,col2_unique 为 3,total_unique 3

我可以为 col1 和 col2 添加选择,然后从选择中添加不同的值,但是有更好(更好)的方法来解决任务吗?

postgresql distinct-values
1个回答
0
投票

列值的标记联合,然后是条件聚合,看起来和阅读起来会更好。但不一定更有效率。

with t as (
  select col1 as col, 1 as tag from the_table
  union all
  select col2, 2 from the_table
)
select count(distinct col) filter (where tag = 1),
       count(distinct col) filter (where tag = 2),
       count(distinct col)
from t;

演示

© www.soinside.com 2019 - 2024. All rights reserved.