SQL Server using pivot/unpivot in a new table -


needless say, trying understand pivot/unpivot topic in last few days no hope. not understand pivot , unpivot. have table: table called natalie_playground.

buildingname    billingmonth    consumption  building1       1/1/2011        59318  building2       1/1/2011        6962  building3       1/1/2011        204300  building4       1/1/2011        69600  building5       2/1/2011        47316  building6       2/1/2011        162300  building7       2/1/2011        7122  building8       2/1/2011        7444 

i not know if have use pivot or unpivot make table looks this:

buildingname    january      february    march  .... december  building1       59318        47316  building2       6962         162300  building3       204300       162300  building4       69600        7444 

you want use pivot function convert rows of data columns:

select buildingname, january, february, march, april (   select buildingname,     datename(month, billingmonth) month,     consumption   yourtable ) d pivot (   sum(consumption)   month in (january, february, march, april) ) piv; 

see sql fiddle demo. unpivot function used take multiple columns , convert them multiple rows of data.


Comments