【问题标题】:How to count both null values as well as distinct values of non-null columns in a table如何计算空值以及表中非空列的不同值
【发布时间】:2017-11-01 07:39:25
【问题描述】:

我有我认为应该是一个简单的查询,但它可能毕竟不是。我需要在一个查询中做两件事(最好):

  1. 计算值为 NULL 的 #of recs(在多列中)
  2. 计算特定列上的不同记录数

基本上,该表是索赔数据的列表,并按以下方式组织...

  1. 一个索赔编号可以出现多次。我想计算不同的索赔编号(此字段永远不会为 NULL)
  2. NULL 值可以出现在一个或多个列中

样本数据:

insert into t1 (ID, LOB, Funding, Claim_ID, Claim_Type, Pharmacy_ID)
values (3617623, 'DRUG', NULL, 2389753478, 'ORG', 'OA734'),
(3462090, 'DRUG', NULL, 2389753478, 'REV', 'OA734'), 
(3587262, NULL, NULL, 5356201834, 'ORG', NULL), 
(3160932, 'DRUG', NULL, 4627282840, 'ORG', NULL), 
(3986523, 'DRUG', NULL, 4627282840, 'REV', NULL), 
(3874627, 'DRUG', NULL, 7735624780, 'ORG', '43857')

预期结果:

  1. 总记录数 = 6
  2. Claim_ID 计数 = 4
  3. NULL LOB 计数 = 1
  4. NULL Funding 计数 = 4
  5. NULL Claim_Type 的计数 = 0
  6. NULL Pharmacy_ID = 2 的计数

我尝试了这个查询,但效果不佳:

select
sum (case when LOB is null then 1 else 0 end) as LOB_null,
sum (case when Funding is null then 1 else 0 end) as Funding_null,
sum (case when Claim_Type is null then 1 else 0 end) as Claim_Type_null,
sum (case when Pharmacy_ID is null then 1 else 0 end) as Pharmacy_ID_null,
sum (count (distinct (case when claim_id is not null then 1 end)) as ttl_claims,
sum (case when ID is not null then 1 end) as ttl_recs
from t1

【问题讨论】:

    标签: null amazon-redshift distinct-values


    【解决方案1】:

    您需要为满足指定条件的行计算不同的claim_id,而不是计算记录:

    select
    sum (case when ID is not null then 1 end) as ttl_recs,
    count (distinct case when claim_id is not null then claim_id end) as ttl_claims,
    count (distinct case when LOB is null then claim_id end) as LOB_null,
    count (distinct case when Funding is null then claim_id end) as Funding_null,
    count (distinct case when Claim_Type is null then claim_id end) as Claim_Type_null,
    count (distinct case when Pharmacy_ID is null then claim_id end) as Pharmacy_ID_null
    from t1
    

    如果有任何更改,相同的claim_id 可以在一行中有 2 行具有 NULL 属性,而在另一行中具有 NOT NULL 您必须先按 claim_id 分组以解决您想要的冲突,然后生成该摘要聚合

    【讨论】:

    • THNXS 这么多@AlexYes 为您解答!您对我解决问题的尝试的修改有效!我认为我需要找到一种方法来使解决方案更有效。就目前而言,运行 26,957,022 条记录需要 4m 和 58s
    • @Gar 您的表格是由claim_id 排序/分配的吗?
    • 抱歉回复晚了。该表位于 Amazon 的 Redshift 中,我仍在学习如何解决该数据库的特殊性。但是要回答您的问题,我不确定。我想认为 ID 和 Claim_ID 列是表中的键,但我只是尝试运行 pg_table_def 命令并没有得到任何回复
    • 最好重新创建以SORTKEY (claim_id)结尾的表,插入数据并运行VACUUMANALYZE,然后检查查询是如何工作的。 Sortkey 将确保具有相同claim_id 的行在磁盘上在一起,因此计数更有效
    • 有道理;我会和我们的 dba 一起提出来,看看他怎么说
    猜你喜欢
    • 2019-10-11
    • 1970-01-01
    • 2011-11-05
    • 2019-09-03
    • 1970-01-01
    • 2021-11-05
    • 2014-07-27
    • 2019-12-20
    • 2015-08-25
    相关资源
    最近更新 更多