问题描述
||
我试图选择一个字段的名称,该字段最经常出现在表中并且其中某个值是true。
Select
Max(Count(Name))
From
EmployeeTreats
Where
Donut = \"Yes\"
And
AmountEaten >= 10
错误:无法执行汇总
对包含
集合或子查询。
我要寻找的显然是这样的:Edward has eaten the most with a sum total of 45
Name
Edward
解决方法
这将处理多个相同名称的名称的情况。
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 )
, 根据您最初的问题:
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;
, 诀窍是按名称分组。然后按count(*)降序排列,并剪掉顶部的1。
select top 1 max(name)
from employeeTreats
where donut=\'Yes\'
and amountEaten >= 10
group by name
order by count(*) desc