根据一列的相似性检查所有其他列的更改(续)

时间:2015-07-10 16:55:54

标签: mysql sql sql-server-2008

select sum(case when NumFirstNames <> 1 then 1 else 0 end) as DifferentFirstNames,
   sum(case when NumLastNames <> 1 then 1 else 0 end) as DifferentLastNames,
   sum(case when NumSSN <> 1 then 1 else 0 end) as DifferentSSN,
   sum(case when NumPhone <> 1 then 1 else 0 end) as DifferentPhone       
from (select EncounterId, count(*) as Num,
count(distinct FirstName) as NumFirstNames,
count(distinct LastName) as NumLastNames,
count(distinct SSN) as NumSSN,
count(distinct Phone) as NumPhone
from table t
group by EncounterId) e;

我需要上面的查询按照名为FacilityCode的表中的另一列进行分组,并按列显示重复的EncounterID和NO缺陷的次数。

此外,是否可以使用类似构建的查询来提取&#34;缺陷&#34;结果只是计数(即第一个查询结果背后的数据)?

请参阅上一个问题的链接: Check for changes in all other columns based on similarities one column

1 个答案:

答案 0 :(得分:0)

是。只需将列放在子查询中并在外部查询中聚合:

select FacilityCode,
       sum(case when NumFirstNames <> 1 then 1 else 0 end) as DifferentFirstNames,
       sum(case when NumLastNames <> 1 then 1 else 0 end) as DifferentLastNames,
       sum(case when NumSSN <> 1 then 1 else 0 end) as DifferentSSN,
       sum(case when NumPhone <> 1 then 1 else 0 end) as DifferentPhone       
from (select EncounterId, FacilityCode, count(*) as Num,
             count(distinct FirstName) as NumFirstNames,
             count(distinct LastName) as NumLastNames,
             count(distinct SSN) as NumSSN,
             count(distinct Phone) as NumPhone
      from table t
      group by EncounterId, FacilityCode
     ) e
group by FacilityCode;

我不知道你的意思是“拉出缺陷结果”。但子查询(可能带有合适的having子句)将获取每个EncounterId的信息。