0

With table "Groceries" having columns "Name" and "Item", with the format:

*Name* | *Item*
 Bill  |  Eggs
 Bill  |  Milk
 Sam   |  Eggs
 Sam   |  Turkey
 Sam   |  Butter
 Josh  |  Milk
 Josh  |  Butter

I'm looking to generalize a query to cast these "Items" out into their own columns, acting as flags.

My current query is essentially:

SELECT
   MAX(CASE WHEN grocery.Item = 'Eggs' THEN 1 ELSE 0 END) 'Eggs',
   MAX(CASE WHEN grocery.Item = 'Milk' THEN 1 ELSE 0 END) 'Milk',
   MAX(CASE WHEN grocery.Item = 'Turkey' THEN 1 ELSE 0 END) 'Turkey',
   MAX(CASE WHEN grocery.Item = 'Butter' THEN 1 ELSE 0 END) 'Butter'
FROM
   Groceries grocery

which works, but I want to generalize it somehow so that rather than listing out each unique value and using this "MAX(CASE WHEN" logic on each one, the query does this automatically for whichever distinct values are in the grocery.Item column.

Is there any way to do this generalization, or will I simply have to list out each value? Thanks in advance.

mizichael
  • 57
  • 1
  • 6

1 Answers1

0

First of all create the select clause:

DECLARE @SELECT VARCHAR(MAX)=''

SELECT @SELECT = @SELECT + ',MAX(CASE WHEN grocery.Item =''' + ITEM + ''' THEN 1 ELSE 0 END)  ['+ITEM+']'+CHAR(13) FROM (SELECT DISTINCT ITEM FROM Groceries) grocery
SELECT @SELECT = STUFF(@SELECT,1,1,'')

then create the query and execute it:

DECLARE @QUERY NVARCHAR(MAX)='
    SELECT '+@SELECT+' FROM Groceries grocery
'

EXEC sp_executesql @STMT = @QUERY
Arsalan
  • 709
  • 2
  • 14
  • 27