MS SQL Query显示最大重复列的id

时间:2012-06-15 16:26:05

标签: sql-server sql-server-2012

我有一张桌子

tblDiseaseTrack

TrackID DiseaseID  PostalCode 
1       3          111
2       3          111
3       2          111
4       1          222
5       2          222
6       4          111
7       1          222
8       5          333
9       5          333
10      5          333

我想写一个查询来显示每个邮政编码的最大重复DiseaseId的疾病ID和邮政编码,如下所示:

DiseaseID  PostalCode 
3          111
1          222
5          333

请不要感谢任何帮助。我尝试了evrything并且找不到任何帮助。再次感谢你:)。

1 个答案:

答案 0 :(得分:2)

select diseaseid, postalcode
from 
(
    select
        postalcode, 
        diseaseid,
        row_number() over (partition by postalcode order by count desc) as row
    from 
    (
        select postalcode, count(postalcode) as count, diseaseid
        from tblDiseaseTrack
        group by postalcode, diseaseid
    ) as T1
) as T2
where row = 1
order by postalcode

这将完全返回您想要的内容:

DiseaseID  PostalCode 
3          111
1          222
5          333

修改

与上面相同的查询,但是使用JOIN从第二个表中获取城市名称:

select diseaseid, T2.postalcode, city
from 
(
    select
        postalcode, 
        diseaseid,
        row_number() over (partition by postalcode order by count desc) as row
    from 
    (
        select postalcode, count(postalcode) as count, diseaseid
        from @tblDiseaseTrack
        group by postalcode, diseaseid
    ) as T1
) as T2
inner join tblcity on T2.postalcode = tblcity.postalcode
where row = 1
order by postalcode

请注意,我在city表中也使用了相同的列名PostalCode,因此我必须在最外面的查询中为PostalCode添加前缀:T2.postalcode而不是postalcode

否则查询将崩溃并显示以下消息:

  

不明确的列名'邮政编码'

...因为SQL Server不知道我想要的两个PostalCodes中的哪一个。