gpt4 book ai didi

SQL Server 在新表中使用透视/逆透视

转载 作者:行者123 更新时间:2023-12-02 21:56:54 26 4
gpt4 key购买 nike

不用说,我在过去几天试图理解旋转/逆旋转主题,但没有希望。我不明白什么是枢轴,什么是非枢轴。我有这张表:该表称为 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

最佳答案

您将需要使用 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 函数用于获取多列并将它们转换为多行数据。

关于SQL Server 在新表中使用透视/逆透视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17597785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com