Question : Pivot Table with dynamic column headers

Hi all,

I'm trying to pivot some data in a T-SQL query, so it doesnt have to be done manually in Excel.  Just wondering if it was possible, and if so, how.

Basically 2 sections to the question, 1. Have the column names (product and date) be dynamic.  2. Have 2 column headers, showing each date, and all products that fall under that date.

Please see attached code section for sample table and desired output.

Hopefully this is clear, but if anymore info is required just ask.

Thanks,
Al
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
Sample Table:
 
ID	| PRODUCT	| DATE
-----------------------
1	| PROD_A	| 01/01/2009
1	| PROD_A	| 01/01/2009
1	| PROD_B	| 02/02/2009
1	| PROD_C	| 02/02/2009
2	| PROD_A	| 02/02/2009
2	| PROD_B	| 03/03/2009
2	| PROD_B	| 03/03/2009
3	| PROD_A	| 01/01/2009
3	| PROD_A	| 02/02/2009
3	| PROD_A	| 03/03/2009
3	| PROD_B	| 03/03/2009
3	| PROD_B	| 04/04/2009
3	| PROD_C	| 02/02/2009
4	| PROD_B	| 02/02/2009
4	| PROD_B	| 02/02/2009
4	| PROD_B	| 02/02/2009
 
.
Desired Pivot Output:
     __________________________________________________________________________
    |    01/01/2009  |         02/02/2009       |    03/03/2009   | 04/04/2009 |
    |      PROD_A    | PROD_A | PROD_B | PROD_C | PROD_A | PROD_B |     PROD_B | 
    ----------------------------------------------------------------------------
1   |        2       |        |    1   |   1    |        |        |            |
2   |                |     1  |        |        |        |    2   |            |
3   |        1       |     1  |        |   1    |    1   |    1   |      3     |
4   |                |        |    1   |        |        |        |            |
Open in New Window Select All

Answer : Pivot Table with dynamic column headers

what about this?
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
CREATE TABLE #Temp (ID int, Product nvarchar(30), Dates datetime)
INSERT INTO #Temp VALUES (1, 'PROD_A', '01/01/2009')
INSERT INTO #Temp VALUES (1, 'PROD_A', '01/01/2009')
INSERT INTO #Temp VALUES (1, 'PROD_B', '02/02/2009')
INSERT INTO #Temp VALUES (1, 'PROD_C', '02/02/2009')
INSERT INTO #Temp VALUES (2, 'PROD_A', '02/02/2009')
INSERT INTO #Temp VALUES (2, 'PROD_B', '03/03/2009')
 
 
begin
DECLARE @Cols NVARCHAR(2000)
SET @Cols=''
SELECT @Cols=@Cols+ '['+convert(varchar(50),s.Dates) + ' ' + s.product +']'+ ', ' FROM
(SELECT DISTINCT Dates,Product FROM #Temp) AS s
 
SET @Cols=LEFT(@Cols,LEN(@Cols)-1)
print @cols
SET @Cols='SELECT * from (select id as ids,ID,convert(varchar(50),dates) + '' '' +Product as dates FROM #Temp) up
PIVOT (count(ID) for dates in ('+@cols+')) AS pivo'
--print @cols
EXECUTE sp_executeSQL @Cols
end
go
 
 
DROP TABLE #temp
Open in New Window Select All
Random Solutions  
 
programming4us programming4us