2011-05-27 60 views
0

我試圖選擇一個字段的名稱,該字段最常出現在表中,並且其中的某個值爲true。SQL Server 2008:選擇具有最高重複值的列的名稱

Select 
     Max(Count(Name)) 
From 
     EmployeeTreats 
Where 
     Donut = "Yes" 
     And 
     AmountEaten >= 10 

Error: Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

我所尋找的顯然是這樣的:Edward has eaten the most with a sum total of 45

Name 
Edward 
+0

你需要告訴我們你的表是什麼樣的。如果你有'AmountEaten'作爲一個字段,爲什麼不使用它? – JNK 2011-05-27 16:20:27

回答

0

這將處理多個名稱具有相同計數的情況。

select Name, count(*) 
from ExployeeTreats 
where Donut = "Yes" and AmountEaten >= 10 
group by Name 
having count(*) >= ALL (select count(*) 
         from EmployeeTreats 
         where Donut = "Yes" and AmountEaten >= 30 
         group by Name) 
1

根據您最初的問題:

select top (1) 
     [Name] 
    , count(1) as Cnt 
from Employees 
where Donut = 'yes' 
    and AmountEaten >= 10 
group by [Name] 
order by Cnt desc; 

您的編輯後:

select top (1) 
     [Name] 
    , sum(AmountEaten) as TotalEaten 
from Employees 
where Donut = 'yes' 
group by [Name] 
order by TotalEaten desc; 
0

訣竅是按名稱分組。然後按數量(*)降序排列,並剪掉頂部1.

select top 1 max(name) 
    from employeeTreats 
where donut='Yes' 
    and amountEaten >= 10 
group by name 
order by count(*) desc 
相關問題