Wednesday, March 7, 2012

Pivoting Row Values into Colums

I'd like to get some data which includes month values bound to a data grid. The data is stored in a table like so:

Measure Month Value
A June 10.00
A July 9.00
A Aug 11.00
B Jun 100.00
B Jul 98.00
B Aug 99.00
C Jun 0.75
C Jul 0.8
C Aug 0.91

I need to report the data like this:
Measure Jun Jul August
A 10 9 11
B 100 98 99
C 75% 80% 91%

This was simple in classic ASP. Just use two recordsets, create a new table cell for each month using the first recordset then use the second recordset for each row.

But is there a way to "Pivot" or rotate the data so I can use the DataGrid? It only seems possible if each month has its own column field in table. Each month add a new column.

I can restructure the database, if needed.

I thought about creating a Cube, but that seems to have its own limitations. For example what if I want to add a Column for Quarter and year totals? I don't think it's possible to show multiple planes like that in an query of a cube.

It seems that this might be resolved in the presentation layer or the data layer. Any Suggestions?You can write a view or a stored procedure to produce the result set in your prefered format. The code below will only work when the same month has the same spelling in all rows. E.x., for June, always use either Jun or June. In the following example, I am assuming, Jun, Jul and Aug are used.


Select measure,
MAX(CASE [Month] WHEN 'Jun' THEN Value END) AS Jun,
MAX(CASE [Month] WHEN 'Jul' THEN Value END) AS Jul,
MAX(CASE [Month] WHEN 'Aug' THEN Value END) AS Aug
From YourTable
Group By Measure

Then you can bind the returned result set to your datagrid.

No comments:

Post a Comment