交叉制表Msg 8120,Level 16,State 1,Line 8

时间:2013-11-05 13:52:01

标签: sql pivot sql-server-2012-express

我正在尝试在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

但我收到错误:

  

Msg 8120,Level 16,State 1,Line 8

     

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

1 个答案:

答案 0 :(得分: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