I have the following table…let’s call it Table1
TERM PERIOD Average StandardDeviation Minimum
+ 1 Period 2012Q3 0.00417 0.00722 0
+ 120 Periods 2012Q3 0.02951 0.0014 0.028615
+ 20 Periods 2012Q3 0.009898 0.0037 0.007612
+ 40 Periods 2012Q3 0.018255 0.00262 0.016565
+ 1 Period 2012Q4 0.005 0.007 0
+ 120 Periods 2012Q4 0.026 0.001 0.03
+ 20 Periods 2012Q4 0.007 0.003 0.0042
+ 40 Periods 2012Q4 0.018 0.002 0.0165
Is there a way to code this so I can have a table that looks like so:
TERM PATHS 2012Q3 2012Q4
+ 1 Period Average 0.00417 0.005
+ 1 Period StandardDeviation 0.00722 0.007
+ 1 Period Minimum 0 0
…and so on for each TERM ( + 120 Periods, + 40 Periods, etc).
To produce this result, you will want to use both the
UNPIVOTand thePIVOTfunction. TheUNPIVOTtakes the columnsAverage,StandardDeviationandMinimumand converts them into multiple rows. Once you have the rows, then you can apply thePIVOTto thePeriodvalues. Your code will be similar to this:See SQL Fiddle with Demo.
This can also be done using a
UNION ALLto unpivot the data and an aggregate function with aCASEexpression to pivot:See SQL Fiddle with Demo.
The above versions work great if you have a known number of
periodvalues. If you don’t then you will want to use dynamic sql to generate the result:See SQL Fiddle with Demo.
All of the versions produce the same result.