Pivot Rows to Columns Dynamically based on selected records without creating temporary table

48 Views Asked by At

I have written a SQL query to extract year 2000 to 2002 records from a data table in SQL Server with columns - Year, Month and Value and 'Month' pivot from row to column dynamically.

However, the pivot column extracted all the months in the data table instead of basing on the selected years which is not what I want. How do I modify my SQL code to extract only the months for the selected years as columns without creating any temporary table as I do not have any write or table create access in the SQL Server?

Sample data table:

Year    Month   Amount
----------------------
2000    Jan 1000
2000    Feb 2000
2000    Mar 3000
2000    Apr 4000
2000    May 5000
2000    Jun 6000
2001    Jan 4500
2001    Apr 4500
2001    Jul 6000
2001    Oct 6000
2002    Mar 3000
2002    Jun 6000
2002    Sep 9000
2003    Oct 2500
2003    Nov 3500
2003    Dec 5000
2004    Jul 6000
2004    Aug 5000
2004    Sep 4000
2004    Oct 3000
2004    Nov 2000
2004    Dec 1000

My SQL code:

DECLARE @col NVARCHAR(MAX);
DECLARE @sql NVARCHAR(MAX);

SET @col = 
(Select STRING_AGG([Month], ',') 
FROM
(Select distinct [Month] from [dbo.DataTable) t);

SET @sql =
'Select Year, ' + @col + '
from 
(SELECT 
Year, 
Month, 
Value
    
FROM [dbo.DataTable]) as S
PIVOT (
    MAX(Value) 
    FOR Month IN (' + @col + ')
) as P
WHERE [Year] IN (
    ''2000'',
    ''2001'',
    ''2002''
) ORDER BY [Year]'

EXECUTE (@sql)

Query result:

Year    Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
------------------------------------------------------------
2000    1000    2000    3000    4000    5000    6000                        
2001    4500            4500            6000            6000        
2002            3000            6000            9000            

The result displays all the Months in the DataTable even though year 2000 to 2002 do not have Aug, Nov and Dec months.

0

There are 0 best solutions below