0

我正在尝试在 sql server express 2012 中执行以下操作

SELECT t,     
  MAX(CASE ItemID WHEN 1 THEN qun  ELSE  '' END) AS [Item-A],    
  MAX(CASE ItemID WHEN 2 THEN qun  ELSE  '' END) AS [Item-B],    
  MAX(CASE ItemID WHEN 3 THEN qun  ELSE  '' END) AS [Item-C],
  MAX(CASE ItemID WHEN 4 THEN qun  ELSE  '' END) AS [Item-D],
  MAX(CASE ItemID WHEN 5 THEN qun  ELSE  '' END) AS [item-E]
FROM 
(
   SELECT  CONVERT(char(7),Production.Production.[Date] , 112)as t, 
        sum(Production.Production.Quantity) qun, 
        Production.Production.ItemID ItemID
    FROM    Production.Production 
)AS e 
GROUP BY e.t

但我收到错误:

消息 8120,第 16 层,状态 1,第 8 行

列“Production.Production.Date”在选择列表中无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

4

1 回答 1

1

由于您在子查询中使用聚合函数,因此您需要对选择列表中未聚合的列使用 GROUP BY 函数。您需要添加以下行:

GROUP BY CONVERT(char(7),Production.Production.[Date] , 112), Production.Production.ItemID

因此,您的完整查询将是:

SELECT t,     
    MAX(CASE ItemID WHEN 1 THEN qun  ELSE  '' END) AS [Item-A],    
    MAX(CASE ItemID WHEN 2 THEN qun  ELSE  '' END) AS [Item-B],    
    MAX(CASE ItemID WHEN 3 THEN qun  ELSE  '' END) AS [Item-C],
    MAX(CASE ItemID WHEN 4 THEN qun  ELSE  '' END) AS [Item-D],
    MAX(CASE ItemID WHEN 5 THEN qun  ELSE  '' END) AS [item-E]
FROM 
(
    SELECT  
        CONVERT(char(7),Production.Production.[Date] , 112) as t, 
        sum(Production.Production.Quantity) qun, 
        Production.Production.ItemID ItemID
    FROM    Production.Production 
    GROUP BY CONVERT(char(7),Production.Production.[Date] , 112), Production.Production.ItemID
)AS e 
GROUP BY e.t
于 2013-11-05T13:58:27.557 回答