Suppose, we have the table “tblSample” with the following data.
The query to transform the Columns of this table to Rows:
Seq | Month | New Policy Count | New Premium | Claims Recorded | Claims Cost | Loss Ratio |
1 | 2010/06/01 | 1000 | 100000.9 | 5 | 66666.98 | 66.66 |
2 | 2010/05/01 | 1100 | 200000.9 | 10 | 55555.98 | 27.77 |
3 | 2010/04/01 | 1200 | 300000.9 | 15 | 44444.98 | 14.81 |
4 | 2010/03/01 | 1300 | 400000.9 | 20 | 33333.98 | 8.33 |
5 | 2010/02/01 | 1400 | 500000.9 | 25 | 22222.98 | 4.44 |
6 | 2010/01/01 | 1500 | 600000.9 | 30 | 11111.98 | 1.85 |
The query to transform the Columns of this table to Rows:
SELECT Seq
,ROW_NUMBER() OVER(PARTITION BY [Month] ORDER BY Seq) AS 'RowNumber'
,CONVERT(VARCHAR, [Month], 111) AS [Month], Title, aValue
,CONVERT(VARCHAR, [Month], 111) AS [Month], Title, aValue
INTO #temp
FROM
(SELECT Seq
,[Month]
,[New Policy Count]
,[Month]
,[New Policy Count]
,[New Premium]
,[Claims Recorded]
,[Claims Cost]
,[Loss Ratio]
,[Claims Recorded]
,[Claims Cost]
,[Loss Ratio]
FROM tblSample) p
UNPIVOT
(aValue FOR Title IN ([New Policy Count],[New Premium],[Claims Recorded],[Claims Cost],[Loss Ratio]))
(aValue FOR Title IN ([New Policy Count],[New Premium],[Claims Recorded],[Claims Cost],[Loss Ratio]))
AS unpvt
DECLARE @SQLQuery VARCHAR(MAX)
,@PivotColumns VARCHAR(MAX)
SET @PivotColumns = ''
SELECT @PivotColumns = @PivotColumns+ '['+ [Month] +'],' FROM (SELECT
DISTINCT [Month] FROM #TEMP) a
DISTINCT [Month] FROM #TEMP) a
SET @PivotColumns = SUBSTRING(@PivotColumns, 1,LEN(@PivotColumns) - 1)
SET @SQLQuery = 'SELECT Title,' + @PivotColumns +
'FROM (SELECT [Month], RowNumber, Title, aValue FROM #temp) s
PIVOT (SUM(aValue) FOR [Month] IN (' + @PivotColumns + ')) p
ORDER BY RowNumber'
PIVOT (SUM(aValue) FOR [Month] IN (' + @PivotColumns + ')) p
ORDER BY RowNumber'
EXEC (@SQLQuery)
DROP TABLE #temp
The final output looks like:Title | 2010/01/01 | 2010/02/01 | 2010/03/01 | 2010/04/01 | 2010/05/01 | 2010/06/01 |
New Policy Count | 1500 | 1400 | 1300 | 1200 | 1100 | 1000 |
New Premium | 600000.9 | 500000.9 | 400000.9 | 300000.9 | 200000.9 | 100000.9 |
Claims Recorded | 30 | 25 | 20 | 15 | 10 | 5 |
Claims Cost | 11111.98 | 22222.98 | 33333.98 | 44444.98 | 55555.98 | 66666.98 |
Loss Ratio | 1.85 | 4.44 | 8.33 | 14.81 | 27.77 | 66.66 |
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.