为什么列无效,因为它不在聚合函数或group by子句中?

时间:2014-11-28 10:39:12

标签: sql-server group-by

我正在尝试在SQL Server中执行以下查询:

Select *, sum(Quantity) as Quantity from tblDeal where buyercode = 25 
and dealdate >= '2014/04/01' and dealdate <= '2015/03/31' 
group by dealno order by DealDate, DealNo

我收到以下错误:

ERROR [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]
Column 'tblDeal.dealid' is invalid in the select list because it is not 
contained in either an aggregate function or the GROUP BY clause.

tbldeal.dealid实际上是tbldeal表中存在的多个列之一。

我在互联网上搜索了解决方案,但在大多数情况下,人们建议将列添加到group by子句或添加聚合函数。这些操作可能会删除错误但可能会影响最终结果。我的要求是保持数据按dealno分组。我该怎么办?请帮助。

2 个答案:

答案 0 :(得分:1)

如果您使用聚合函数,则不能SELECT *,因为您必须GROUP BY这些函数中未包含的所有内容(除非GROUP BY *中包含所有列}})。

删除*并仅添加相关列,并GROUP BY添加:

SELECT DealNo, 
       col1, 
       col2, 
       DealDate,
       SUM(Quantity) AS Quantity 
FROM   tblDeal 
WHERE  buyercode = 25 
       AND DealDate >= '2014/04/01' 
       AND DealDate <= '2015/03/31' 
GROUP  BY DealNo, 
          col1, 
          col2 
          DealDate
ORDER  BY DealDate, 
          DealNo 

如果您只想GROUP BY DealNo,除了聚合函数之外,您必须SELECT DealNo,或者也可以使用其他列的聚合函数(如MAX或任何其他符合您需求的):

SELECT DealNo, 
       MAX(col1), 
       MAX(col2), 
       MAX(DealDate) AS dd,
       SUM(Quantity) AS Quantity 
FROM   tblDeal 
WHERE  buyercode = 25 
       AND DealDate >= '2014/04/01' 
       AND DealDate <= '2015/03/31' 
GROUP  BY DealNo
ORDER  BY dd, 
          DealNo 

假设您有两行:

DealNo | col1 | col2 | DealDate   | Quantity
     1 |    0 |    1 | 2014/04/02 |       10
     1 |    2 |    3 | 2014/04/02 |       10

如果在选择col1和col2时只有GROUP BY DealNo,那么您期望SQL Server将哪些值放入col1和col2结果?

答案 1 :(得分:0)

您也可以写为:

Select *,
       sum(Quantity) OVER ( PARTITION BY dealno ORDER BY dealno ASC) as Quantity 
from @tblDeal where buyercode = 25 
and dealdate >= '2014/04/01' and dealdate <= '2015/03/31' 
--group by dealno 
order by DealDate, DealNo