Thursday, October 31, 2013

use of PIVOT operator dynamically

Another solution,



create table #temp(dtDate datetime,Category varchar(10),Amount decimal(10,2),Notes varchar(20))
insert into #temp values('2013-01-15 00:00:00.000','Cat1',10.00,NULL)
insert into #temp values('2013-01-16 00:00:00.000','Cat2',25.00,NULL)
insert into #temp values('2013-02-15 00:00:00.000','Cat1',25.00,NULL)
insert into #temp values('2013-02-17 00:00:00.000','Cat3',14.00,NULL)
insert into #temp values('2013-03-10 00:00:00.000','Cat2',10.00,NULL)
insert into #temp values('2013-03-02 00:00:00.000','Cat4',120.00,NULL)
insert into #temp values('2013-04-20 00:00:00.000','Cat5',60.00,NULL)
insert into #temp values('2013-04-29 00:00:00.000','Cat2',10.00,NULL)
insert into #temp values('2013-05-05 00:00:00.000','Cat3',15.00,NULL)
insert into #temp values('2013-05-21 00:00:00.000','Cat4',20.00,NULL )
-------------------
DECLARE
@cols nvarchar(max),
@stmt nvarchar(max)
SELECT @cols = isnull(@cols + ', ', '') + '[' + T.MonthYear + ']' FROM
(SELECT distinct datename(m,dtDate) + '_' + cast(year(dtDate) as varchar(4)) MonthYear from #temp) as T
SELECT @stmt = '
SELECT *
FROM (select Category, Amount,datename(m,dtDate) + ''_'' + cast(year(dtDate) as varchar(4)) MonthYear from #temp) as T
PIVOT
(
Sum(Amount) For MonthYear In (' + @cols + ')
) as P'
exec sp_executesql @stmt = @stmt





Regards, RSingh


No comments:

Post a Comment