下面的查询是计算缺陷'在我的数据中,意味着任何时候EncounterID匹配但其他列不匹配。如何修改查询以不包含任何“缺陷”。由NULL值引起?
SELECT FacilityCode,
AdmitDate,
SUM(CASE
WHEN NumFirstName <> 1 THEN 1
ELSE 0
END) AS DifferentFirstNames,
SUM(CASE
WHEN NumLastName <> 1 THEN 1
ELSE 0
END) AS DifferentLastNames,
SUM(CASE
WHEN NumPhone <> 1 THEN 1
ELSE 0
END) AS DifferentPhone,
'Defect' Label
FROM (SELECT EncounterId,
FacilityCode,
AdmitDate,
COUNT(*) AS Num,
COUNT(DISTINCT LEFT(FirstName, 4)) AS NumFirstName,
COUNT(DISTINCT LastName) AS NumLastName,
COUNT(DISTINCT Phone) AS NumPhone,
FROM [BINextGen].[dbo].[tbFCCDefectReport]
GROUP BY EncounterId,
facilitycode,
AdmitDate) e
GROUP BY FacilityCode,
AdmitDate;
以下是目前的情况:
示例数据:
FacilityCode AdmitDate FirstName LastName
BOHG 7-1-15 Justin Kelley
BOHG 7-1-15 Justin NULL
AARD 7-1-15 James Smith
AARD 7-1-15 James Smith
示例输出:
FacilityCode AdmitDate DifferentFirstNames DifferentLastNames
BOHG 7-1-15 0 1
AARD 7-1-15 0 0
我想忽略第一个姓氏更改,因为它是NULL并且在输出中全部为0(我只关心是否有更改,例如Kelley更改为Kelly):
期望的输出:
FacilityCode AdmitDate DifferentFirstNames DifferentLastNames
BOHG 7-1-15 0 0
AARD 7-1-15 0 0
答案 0 :(得分:0)
此SQL fiddle为您提供了所要求的结果......但我不确定它会一直有效。我不确定为什么你的方法不起作用我所做的就是消除代码中的错误并删除不需要的字段...计数按预期工作。
SELECT FacilityCode,
AdmitDate,
SUM(CASE
WHEN NumFirstName <> 1 THEN 1
ELSE 0
END) AS DifferentFirstNames,
SUM(CASE
WHEN NumLastName <> 1 THEN 1
ELSE 0
END) AS DifferentLastNames
FROM (SELECT
FacilityCode,
AdmitDate,
COUNT(*) AS Num,
COUNT(DISTINCT LEFT(FirstName, 4)) AS NumFirstName,
COUNT(DISTINCT LastName) AS NumLastName
FROM [tbFCCDefectReport]
GROUP BY facilitycode,
AdmitDate) e
GROUP BY FacilityCode,
AdmitDate;
可能还有其他两种方法可以提供更好的缩放功能。
一种方法是生成两个不同的数据集,一个&#34;之前&#34;一个&#34;之后&#34;但我不知道如何在没有桌子钥匙的情况下关联数据。
类似
SELECT A.Key,
sum(case when (coalesce(Before.Field1,'') = coalesce(After.Field1,'') OR After.Field1 is null) then 0 else 1 end) as countField1Difference,
sum(case when coalesce(Before.Field2,'') = coalesce(After.Field2,'') OR After.Field2 is null) then 0 else 1 end) as countField2Difference
FROM TableName Before
LEFT JOIN TableName After
on A.Key = B.Key
and B.Bal = 'Something which denotes it as the After set'
and A.Val = 'something which denotes it as the Before set'
GROUP BY A.Key
coalesce处理空值,允许字符串compairison报告
或者你可以使用
Select * from tableName where B.Val = 'something denoting it's the before value'
EXCEPT
Select * from tableName where B.Val = 'something denoting it's the after value'
然而,这显示出任何差异,因为整个差异不是逐列