我有2列
Item | Category
Apple Fruit
Orange Fruit
Potatoes Vegetables
必需的输出:
水果
我试图在数量方面得到最高类别的名称,即Fruit。我写了一个可以在MySql上运行的MySql查询。但是同样的查询会在MS SQL Server上引发错误。任何提示都将不胜感激。
select Cat from (select count(category) as Total,category as cat from test group by category) as S1 group by S1.Total,S1.Cat having max(s1.total)
运行时我得到一个空的结果。但我创建的类似查询在MySql上运行正常:
SELECT s2.cats FROM (SELECT s1.cat AS cats, max(s1.counts) AS countings FROM (SELECT count(category) AS counts, category AS cat from test GROUP BY category) AS s1) AS s2
我得到的错误信息是:消息4145,级别15,状态1,行1 在预期条件的上下文中指定的非布尔类型的表达式,接近'。'。
我想避免使用TOP
答案 0 :(得分:0)
这样的东西?相当丑陋,但避免顶部。此外,将返回所有具有最大计数的项目,而不仅仅是任意项目。
假设表[食物]的列类别为:
select category from Food group by Category having COUNT(*) =
(select max(cnt) from (select COUNT(*) as cnt from Food group by Category) subq)