Tuesday, 17 December 2013

Dynamic pivot query in sql

DECLARE @year AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select  @year= coalesce(@year+',['+cast((Year) as varchar(4))+']','['+cast(Year as varchar(4))+']')
from (select distinct  Year(OrderDate) year from [Sales].[SalesOrderHeader])t

set @query='
select Name,'+@year+' from (select p.Name,YEAR(OrderDate) year,LineTotal from  [Sales].[SalesOrderHeader] s
join [Sales].[SalesOrderDetail] o on s.SalesOrderID=o.SalesOrderID
join [Production].[Product] p on o.ProductID=p.ProductID) t
pivot
(
sum(LineTotal)
for year in ('+@year+')
) p1';

exec (@query)


No comments:

Post a Comment