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 を使用して 2 番目のテーブルから都市名を取得します。
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
市区町村テーブルでも同じ列名を使用したことに注意してT2.postalcode
くださいpostalcode
。
そうしないと、クエリが次のメッセージでクラッシュします。
あいまいな列名「郵便番号」
...SQL Server は、2 つの PostalCodes のどちらが必要かを認識できないためです。