列在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中

时间:2014-11-22 13:23:10

标签: sql sql-server syntax

我正在使用以下命令,我得到了大量的结果

 select *
 from sales.SalesOrderDetail
然后我尝试使用以下

 select SalesOrderID, salesorderdetailid, SUM (OrderQty * UnitPrice) as price
 from sales.SalesOrderDetail

 select SalesOrderID, SalesOrderDetailID, SUM (OrderQty * UnitPrice) as price
 from sales.SalesOrderDetail
 group by SalesOrderDetailID
 having SUM(OrderQty * UnitPrice) > 50
 order by ModifiedDate DESC;

我收到错误

Msg 8120, Level 16, State 1, Line 1
Column 'sales.SalesOrderDetail.SalesOrderID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

任何人都可以帮我解释语法吗?

此致 帕诺斯

2 个答案:

答案 0 :(得分:2)

嗯,您在选择列表中的列不在group by中。通常不允许这样做。尝试:

select SalesOrderID, salesorderdetailid, SUM(OrderQty * UnitPrice) as price
from sales.SalesOrderDetail
group by SalesOrderID, salesorderdetailid

select SalesOrderID, SUM(OrderQty * UnitPrice) as price
from sales.SalesOrderDetail
group by SalesOrderID

select salesorderdetailid, SUM(OrderQty * UnitPrice) as price
from sales.SalesOrderDetail
group by salesorderdetailid

我不知道其中哪些(如果有的话)是你真正想要的,但它们确实解决了语法问题。

答案 1 :(得分:0)

因为您在SQL SELECT语句中列出了两个未封装在SUM函数中的列,所以必须使用GROUP BY子句。因此,SalesOrderID,SalesOrderDetailID字段必须列在GROUP BY子句中。

  select SalesOrderID, SalesOrderDetailID, SUM (OrderQty * UnitPrice) as price
     from sales.SalesOrderDetail
     group by SalesOrderID, SalesOrderDetailID
     having SUM(OrderQty * UnitPrice) > 50
     order by ModifiedDate DESC;