T-SQL中的错误8120(嵌套选择命令)

时间:2012-10-11 23:51:47

标签: sql sql-server sql-server-2008 tsql

这句话中我的错误是什么?

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子句中。

2 个答案:

答案 0 :(得分: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 ;

答案 1 :(得分:0)

计数的内部Group By已经使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