2015-11-03 76 views
3

我想比較count(*)值與max(count(*))值,而不使用子查詢塊中的整個查詢。相關示例如下所示。請建議我以最短和最好的方式來達到相同的結果?如何比較Max(Count(*))值而不使用MS SQL中的SubQuery?

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 
) 

回答

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將選擇具有最大計數的所有組)。

+0

謝謝。你讓我今天一整天都感覺很好! :) – Suraj