如何在不使用MS SQL中的SubQuery的情况下比较Max(Count(*))值?

时间:2015-11-03 07:41:51

标签: sql-server

我希望将count(*)值与max(count(*))值进行比较,而不在子查询块中使用整个查询。相关示例如下所示。请建议我获得相同结果的最短和最佳方法?

select ee.LocationName
from Employees ee
inner join EmployeeActivities ea on ee.Username = ea.Username
where ea.Activity = 'Hospital'
group by LocationName
having count(*) =
(
    select max(VisitCount) 
    from (select LocationName, count(*) as VisitCount 
    from Employees e
    inner join EmployeeActivities ea on e.Username = ea.Username
    where ea.Activity = 'Hospital'
    group by e.LocationName) as a
)

1 个答案:

答案 0 :(得分:0)

使用此:

select top 1 with ties ee.LocationName
from Employees ee
inner join EmployeeActivities ea on ee.Username = ea.Username
where ea.Activity = 'Hospital'
group by LocationName
order by count(*) desc

按顺序降序排序并选择前排(with ties将选择所有具有最大数量的组)。