我有我认为应该是一个简单的查询,但可能毕竟不是。我需要在单个查询中做两件事(最好):
- 计算值为 NULL 的 #of 记录(在多列中)
- 计算特定列上 #of 个不同的记录
基本上,该表是索赔数据的列表,并按以下方式组织...
- 一个索赔编号可以多次出现。我想计算不同的索赔编号(此字段永远不会为空)
- 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')
预期成果:
- 总记录数 = 6
- Claim_ID计数 = 4
- 空 LOB 计数 = 1
- 空资金计数 = 4
- 空计数 Claim_Type = 0
- 空计数 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
分组以解决您想要的冲突,然后生成该聚合的摘要