如何计算表中非空列的空值和非空列的不同值



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

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

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

  1. 一个索赔编号可以多次出现。我想计算不同的索赔编号(此字段永远不会为空)
  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. 空 LOB 计数 = 1
  4. 空资金计数 = 4
  5. 空计数 Claim_Type = 0
  6. 空计数 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

您需要对满足指定条件的行计算不同的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 属性,而在另一行中具有 NULL,您必须首先按claim_id分组以解决您想要的冲突,然后生成该聚合的摘要

相关内容

  • 没有找到相关文章

最新更新