毋庸置疑,我试图在最近几天理解枢轴/非透视主题而没有希望。我不明白什么是枢轴,什么是不透明。我有这张桌子:
此表名为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
我不知道是否必须使用pivot或unpivot来使我的表看起来像这样:
BuildingName January February March .... December
Building1 59318 47316
Building2 6962 162300
Building3 204300 162300
Building4 69600 7444
答案 0 :(得分:4)
您需要使用PIVOT函数将数据行转换为列:
select buildingname, January, February, March, April
from
(
select buildingname,
datename(month, billingmonth) month,
consumption
from yourtable
) d
pivot
(
sum(consumption)
for month in (January, February, March, April)
) piv;
见SQL Fiddle with Demo。 UNPIVOT函数用于获取多列并将它们转换为多行数据。