我试图通过计算项目 ID 的出现次数来查找表中排序最多的菜单项。 我尝试了一些不同的事情,但我很迷失。这产生了错误:
"An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference."
但是我认为它体现了我想要实现的目标:
SELECT count(itemCode)
FROM OrderProcessing
WHERE count(itemCode)=max(count(itemCode))
最佳答案
我。原始查询的修改版本 (@DanGuzman 关于关系的评论后更新)
选择与最想要的项目数量相同的所有项目:
SELECT itemCode , count(*) as MaxCount
FROM OrderProcessing
GROUP BY itemCode
HAVING count(*) =
-- count of most wanted item
(select top 1 count(*)
from OrderProcessing
group by itemCode
order by count(*) desc)
二.用于选择最常订购的商品之一的查询
SELECT top 1 itemCode --, count(*) as MaxCount --optional
FROM OrderProcessing
GROUP BY itemCode
ORDER BY count(*) DESC
关于SQL:查找表中列值的最高出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30425545/