【问题标题】:Selecting count of distinct values that are not in another select选择不在另一个选择中的不同值的计数
【发布时间】:2017-11-28 00:04:17
【问题描述】:

我想比较两个表格作为数据质量报告的一部分。结果应该是三个列,汇总了表 table_a 和 table_b 中的 column_x 列:

  1. table_a 中非空白的 column_x 值的百分比
  2. table_a 中不同值的计数
  3. table_a 中不存在于 table_b 中的不同值的计数

第 1 列和第 2 列很容易设置:

select
sum(CASE WHEN column_x = '' THEN 0 ELSE 1 END) / count(*) AS percent_complete_in_a, -- column 1
count(DISTINCT column_x) AS distinct_values_A -- column 2
from table_A

但我不知道如何编写查询,以便第 3 列可以出现在相同的结果中。我尝试了以下几种变体,但每种变体都会在 Postgres 中引发语法错误:

select
sum(CASE WHEN column_x = '' THEN 0 ELSE 1 END) / count(column_x) AS percent_complete_in_a, -- column 1
count(DISTINCT column_x) AS distinct_values_A, -- column 2
count(DISTINCT column_x where column_x not in (select DISTINCT column_x FROM table_b)) as distinct_values_A_except_B -- column 3
from table_a

有没有办法构造这个查询以使其显示所有三列?

【问题讨论】:

    标签: sql postgresql count


    【解决方案1】:

    我相信为此使用左连接会有所帮助。请注意,为避免更改计数,我使用了“选择不同”子查询,该子查询不应与 table_a 中的任何行相乘:

    SELECT
          SUM(CASE WHEN a.column_x = '' OR a.column_x IS NULL 
                     THEN 0 ELSE 1 END) / (COUNT(*) * 1.0)                 AS percent_complete_in_a
        , COUNT(DISTINCT a.column_x)                                       AS distinct_values_a
        , COUNT(DISTINCT case when b.column_x IS NULL then a.column_x end) AS distinct_values_A_except_B
    FROM table_a a
    LEFT JOIN (
          SELECT DISTINCT column_x FROM table_b
          ) b ON a.column_x = b.column_x
    ;
    

    变化:

    • 在第一个 case 表达式中添加了 IS NULL
    • 添加了* 1.0,因此您可以获得百分比的小数结果
    • 左连接并按大小写表达式计数

    【讨论】:

      【解决方案2】:

      我会用子查询来做到这一点:

      select avg( (column_x <> '')::float) as ratio_complete,
             count(distinct column_x) as distinct_values_A, -- column 2
             (count(distinct column_x) -
              (select count(distinct b.column_x)
               from table_b b
               where b.column_x = a.column_x
              )
             ) as distinct_a_not_in_b
      from table_A a;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-03
        • 1970-01-01
        • 1970-01-01
        • 2012-03-05
        • 1970-01-01
        • 2011-02-27
        • 1970-01-01
        相关资源
        最近更新 更多