我有一张桌子
tbl疾病追踪 TrackID 疾病 ID 邮政编码 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
我想写一个查询来显示每个邮政编码的疾病ID和最大重复疾病ID的邮政编码,如下所示,
疾病 ID 邮政编码 3 111 1 222 5 333
请任何帮助将不胜感激。我尝试了一切,但找不到任何帮助..再次感谢您:)
我有一张桌子
tbl疾病追踪 TrackID 疾病 ID 邮政编码 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
我想写一个查询来显示每个邮政编码的疾病ID和最大重复疾病ID的邮政编码,如下所示,
疾病 ID 邮政编码 3 111 1 222 5 333
请任何帮助将不胜感激。我尝试了一切,但找不到任何帮助..再次感谢您:)
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
请注意,我PostalCode
在 city 表中也使用了相同的列名,因此我必须在最外面的查询中添加 PostalCode 前缀:T2.postalcode
而不是postalcode
.
否则查询会因以下消息而崩溃:
不明确的列名“邮政编码”
...因为 SQL Server 不知道我想要两个 PostalCode 中的哪一个。