0

我在这个声明中的错误是什么?

Select Max (TBLvirtual.c2) as MOF --> Most ordered food (MOF)--//
      ,TBLvirtual.c1
from
    (select a.OrdItems as c1, count(a.OrdID) as c2
     from Orderrouter a 
     group by a.OrdItems) as TBLvirtual

我收到了这个错误:

消息 8120,级别 16,状态 1,第 3 行列“TBLvirtual.c1”在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

4

2 回答 2

4

SELECT您在中未包含在聚合函数中的任何字段都必须在 中GROUP BY

Select Max(TBLvirtual.c2) as MOF --> Most ordered food (MOF)--// 
    ,TBLvirtual.c1 
from 
(
    select a.OrdItems as c1 , 
        count(a.OrdID)as c2 
    from Orderrouter a 
    group by a.OrdItems
) as TBLvirtual
group by TBLvirtual.c1  -- add this line

如果你只想要一行(参见SQL Fiddle With Demo):

Select Top 1 c1, c2
from 
(
    select a.OrdItems as c1 , 
        count(a.OrdID)as c2 
    from Orderrouter a 
    group by a.OrdItems
) as TBLvirtual
order by c2 desc

而且你真的不需要派生表:

Select Top 1 
    a.OrdItems as c1 , 
    count(a.OrdID) as c2 
from Orderrouter a 
group by a.OrdItems
order by c2 desc ;
于 2012-10-11T23:58:40.553 回答
0

内部 Group By for count 已经使 C1 唯一,因此无需对它们进行聚合以用于 MAX。做这个

 select a.OrdItems as c1, count(a.OrdID) as c2
 from Orderrouter a 
 group by a.OrdItems
 order by count(a.OrdID) desc

这会给你最高的计数,然后是下一个。如果您想要前 1 名或前 N 名,请执行

Select TOP 1 c1, c2 FROM
(
 select a.OrdItems as c1, count(a.OrdID) as c2
 from Orderrouter a 
 group by a.OrdItems
) TopMost
Order By C2 DESC
于 2012-10-12T00:11:15.200 回答