显示分支数量最多的城市名称

时间:2017-11-21 09:29:24

标签: sql sql-server join group-by count

我试图获得拥有最多分支的城市名称。

select C.City_name ,count(B.B_Name) 
from tblcity C
inner join
tblBranch B
on c.city_id=B.City_id
group by C.City_name
order by count(B.B_Name) desc

以上代码将为我提供特定城市的分支机构数量。 请帮助我解决获得拥有最多分支的城市名称

2 个答案:

答案 0 :(得分:3)

您可以在查询中添加TOP 1

select TOP 1 C.City_name ,count(B.B_Name) 
from tblcity C
inner join
tblBranch B
on c.city_id=B.City_id
group by C.City_name
order by count(B.B_Name) desc

答案 1 :(得分:2)

使用DENSE_RANK()

SELECT
    City_Name, cnt
FROM
(
    SELECT
        c.City_name,
        COUNT(b.B_Name) cnt,
        DENSE_RANK() OVER (ORDER BY COUNT(b.B_Name) DESC) dr
    FROM tblcity c
    INNER JOIN tblBranch b
        ON b.city_id = c.City_id
    GROUP BY c.City_name
) t
WHERE dr = 1;

使用TOP 1 WITH TIES将是另一种选择,但这是SQL Server特有的。