Question

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.

Était-ce utile?

La solution

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top