SQL sum()出错

时间:2014-04-15 06:34:56

标签: sql sql-server

我有这个SQL行

 SELECT No_, sum(Quantity) AS Sold, [Shipment Date] AS SoldDate, [Item Category Code],
 Description, [Description 2] FROM dbo.[3S Company A_S$Sales Invoice Line] 
 WHERE [Item Category Code] = '5104' GROUP BY No_

但是我的脚本出现了这个错误。

Column 'dbo.3S Company A_S$Sales Invoice Line.Shipment Date' is invalid in the select
 list because it is not contained in either an aggregate function or the GROUP BY clause.

任何人都可以帮我解释原因吗?

5 个答案:

答案 0 :(得分:1)

如果在查询中使用GROUP BY,则只允许在分组子句中使用的列和SUM等任何聚合函数在选择列表中使用。在您的情况下,您指定GROUP BY No_,因此这是您可以在不使用聚合函数的情况下选择的唯一列。

如果要获取其余列,可以选择No_和子查询中的其他聚合列,然后通过将No_列与子查询中的相应列匹配来选择其他列。 / p>

答案 1 :(得分:1)

错误意味着您有一个列,在分组时可能有多个值,并且SQL不知道要在列中选择哪个值

你可以使用例如min()选择最小值。喜欢这个

 SELECT No_, 
        sum(Quantity) AS Sold, 
        min([Shipment Date]) AS SoldDate, 
        min([Item Category Code]),
        min(Description), 
        min([Description 2]) 
 FROM dbo.[3S Company A_S$Sales Invoice Line] 
 WHERE [Item Category Code] = '5104' 
 GROUP BY No_

或阅读有关聚合函数以选择合适的函数

BWT它不是MySQL,而是MS SQL(MySQL不会抱怨列使用)

答案 2 :(得分:0)

select子句中存在的列(除了聚合函数之外)也应该出现在group by子句中。这就是错误消息所说的内容。

Select Productid, Sum(Saled) from product 
Group by ProductId

在上面的示例中,ProductId位于group by子句中。这样查询就有效了。如果再引入一个也应该在group by子句中的列,以避免错误。

答案 3 :(得分:0)

您必须在GROUP BY中放置不使用聚合函数的列:

GROUP BY 
    No_
    , [Shipment Date]
    , [Item Category Code]
    , Description
    , [Description 2]

答案 4 :(得分:0)

尝试这个

   SELECT No_, sum(Quantity) AS Sold, [Shipment Date] AS SoldDate, [Item Category Code],
   Description, [Description 2] FROM dbo.[3S Company A_S$Sales Invoice Line] 
   WHERE [Item Category Code] = '5104' GROUP BY No_,[Shipment Date],
   [ItemCategoryCode], Description,[Description 2]

在SQL中,如果您在选择条款中使用任何列名称除了集合功能,那么您需要添加组中的所有列,否则它将显示异常

如果您只想通过NO_ Column进行汇总,那么您必须使用aggregarte函数编写子查询并将其连接到其他列,如下所示

     SELECT No_ ,quant.sold, [Shipment Date] AS SoldDate, [Item Category Code],
   Description, [Description 2] FROM dbo.[3S Company A_S$Sales Invoice Line] INV,
  (SELECT No_, sum(Quantity) AS Sold from dbo.[3S Company A_S$Sales Invoice Line] where 
    WHERE [Item Category Code] = '5104' group by No_) quant


   WHERE [Item Category Code] = '5104' and 
   inv.no_=quant.no_