I know the premise of a PIVOT()
this syntax produces it perfectly for me:
Select *
FROM
(
Select
field1
,annual
,dv As Amt
FROM Testing
) x
pivot
(
SUM(Amt)
,for annual IN ([2014],[2015],[2016])
) p
However, what if I am using a stored procedure and passing a year1 and year2 to the pivot as variables? This will not work as incorrect syntax, but could this be achieved?
Create Procedure dbo.PivotParams
As
Declare @year1 varchar(100), @year2 varchar(100)
Set @year1 = '2014'
Set @year2 = '2016'
Select *
FROM
(
Select
field1
,annual
,dv As Amt
FROM Testing
) x
pivot
(
SUM(Amt) for annual BETWEEN @year1 and @year2
) p
Also the output should use COALESCE
to prevent any NULL
values in any of the pivot columns.
Best Answer
Sure, you can generate the list of years in dynamic SQL, but I suggest passing them as numbers (just one less thing that can go wrong if people pass in bad data, and I'm sure you didn't really mean to hard-code the values inside the procedure, defeats the purpose):
Slightly related: