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

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

我可以添加col 1和col 2的 Select ,然后添加该 Select 中的不同值,但有更好(更好)的方法来解决任务吗?

推荐答案

列值的标记联合,然后进行条件聚合,看起来和读起来都非常好.但不一定非常高效.

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

Demo

Postgresql相关问答推荐

使用PGx在围棋中执行多条SQL语句

mosquito-go-auth with postgres authorization error

有没有一种方法可以在参数中添加密码,并在批处理文件中需要时自动获取密码?

select语句的Jooq代码生成

使用来自 docker 图像的 postgres 设置 Keycloak 21

在 postgres/presto/AWS-Athena 中,与 array_agg( (col1, col2) ) 相反的是什么来获得每组多行?

如何在 MockDataProvider 中创建自定义 JOOQ 记录?

为什么这里的默认格式不同? (ISO 8601 的两种不同实现)

如何将 JSONB 对象数组合并为 PostgreSQL 中的单个对象

MERGE 语句的锁定级别

如何将 NULL 值插入 UUID 而不是零

是否可以在 postgresql 中添加表元数据?

如何 Select 任意行的相邻行(在 sql 或 postgresql 中)?

Django 1.8 数组字段追加和扩展

PostgreSQL:是否可以将枚举转换为整数?

如何在可选参数上查询 postgres?

错误:关系列不存在 PostgreSQL,无法运行插入查询

PostgreSQL - 作为表名的动态值

pgadmin 错误:no password supplied

Rails 5 db 迁移:如何修复 ActiveRecord::ConcurrentMigrationError