문제

I'm trying to execute the following in 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

But I am getting the error:

Msg 8120, Level 16, State 1, Line 8

Column 'Production.Production.Date' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

도움이 되었습니까?

해결책

Since you are using an aggregate function in your subquery you need to use a GROUP BY function for the columns in your select list that are not being aggregated. You need to add the line:

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

So your full query will be:

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top