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
|