我有下一張桌子:
CountryName BrandName Freq
Christmas Island Apple 1
Greece Apple 1
China LG 3
China Samsung 2
United States Ryzen 1
United States Samsung 3
United States Apple 3
如何選擇品牌名稱最頻繁的國家并得到如下結果:
CountryName MostCommBrand
China LG
Christmas Island Apple
Greece Apple
United States Apple
United States Samsung
uj5u.com熱心網友回復:
我建議你使用 RANK。現在也是探索其他排名函式的好時機,因為它們非常有用。
with cte as (
select *, rank () over (partition by countryname order by freq desc) as rnk
from @table)
select * from cte
where rnk = 1
order by countryname, brandname
;
例如,參見小提琴。您可以注釋掉 WHERE 子句以查看 RANK 函式為所有行生成的值,以幫助您了解其作業原理。還要注意小提琴中提供的完整腳本——這是你應該做的事情,以幫助鼓勵其他人幫助你。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414981.html
標籤:
下一篇:有沒有辦法優化這個SQL查詢?
