SQL Server:Group By不工作

时间:2014-12-23 14:14:39

标签: sql-server

我正在构建一个完全正常的查询,直到我尝试GROUP BY tblWJC.WJCNo

查询:

SELECT 
   tblWJCItem.AddedDescription
   ,tblWJC.WJCPrefix + Convert(Varchar(10),tblWJC.WJCNo) AS OurRef
   ,tblWJCItem.MaterialName
   ,tblStockFamily.StockFamily
   ,tblWJCItem.WeightToSend
   ,tblWJC.DateCreated
   ,tblWJC.WJCStatusID
   ,CASE 
       WHEN tblWJC.WJCStatusID < 2 THEN 'Pre Production'
       WHEN tblWJC.WJCStatusID < 4 THEN 'In Production'
       WHEN tblWJC.WJCStatusID > 4 THEN 'Ready To Ship'
       ELSE 'Awaiting Lab Results'
   END  AS [Status]
FROM 
   tblWJC 
INNER JOIN 
   tblWJCItem ON tblWJC.WJCID = tblWJCItem.WJCID 
INNER JOIN 
   tblStockFamily ON tblWJCItem.ProductFamilyID = tblStockFamily.StockFamilyID
INNER JOIN 
   tblCustomer ON tblWJC.CustomerID = tblCustomer.CustomerID
INNER JOIN 
   tblWJCStockStatus ON tblWJC.WJCStatusID = tblWJCStockStatus.WJCStockStatusID
WHERE 
   tblCustomer.CustomerName = 'ROLLS ROYCE' 
   AND tblWJCStockStatus.WJCStockStatus <> 'Stock Usage Confirmed'
GROUP BY 
   tblWJC.WJCNo
ORDER BY 
   tblStockFamily.StockFamily;

任何人都可以指出我的错误吗?我是SQL Server的新手,还在边做边学。

由于

1 个答案:

答案 0 :(得分:0)

通常,当您按字段对查询进行分组时,如果不在select语句的字段中添加聚合函数,则会出现字段聚合错误。在您的情况下,您通过 tblWJC.WJCNo 列进行分组,然后您不会在select语句中聚合您的字段。

SELECT tblWJCItem.AddedDescription
      ,tblWJC.WJCPrefix + Convert(Varchar(10),tblWJC.WJCNo) AS OurRef
      ,tblWJCItem.MaterialName
      ,tblStockFamily.StockFamily
      ,tblWJCItem.WeightToSend
      ,tblWJC.DateCreated
      ,tblWJC.WJCStatusID
      ,CASE WHEN tblWJC.WJCStatusID < 2 THEN 'Pre Production'
            WHEN tblWJC.WJCStatusID < 4 THEN 'In Production'
            WHEN tblWJC.WJCStatusID > 4 THEN 'Ready To Ship'
            ELSE 'Awaiting Lab Results'
            END  AS [Status]

如果按字段分组并且想要在select语句中放入其他字段,则这些字段应该聚合或包含在group by语句中,这似乎是合乎逻辑的,因为如果按字段对数据进行分组,则其他字段应按字段按字段聚合以显示它们。

这是一个包含SQL Server中所有聚合函数的链接:
http://msdn.microsoft.com/en-us/library/ms173454.aspx