gpt4 book ai didi

sql-server - 对多列进行透视 (T-SQL)

转载 作者:行者123 更新时间:2023-12-05 01:20:33 25 4
gpt4 key购买 nike

我有这组数据(操作列表),已经清理并准备好进行 PIVOT 操作。

enter image description here

我怎样才能实现这样的目标(汇总操作的数量;持续时间;总值;净值……按月)?

enter image description here

(准备 MS 认证并且非常沮丧,因为我无法使用 PIVOT 解决这个问题)

最佳答案

首先你需要unpivot数据然后你可以pivot结果

示例数据

  create table piv(TimeRange varchar(50),Type varchar(50), Month int,ActionDuration int, GrossValue bigint, NetValue bigint)

insert piv values
('09:00-10:00','Bonus' ,1 ,30 ,0 ,0 ),
('09:00-10:00','Bonus' ,1 ,30 ,0 ,0 ),
('09:00-10:00','Billed' ,1 ,30 ,77982 ,701838 ),
('09:00-10:00','Not Billed' ,1 ,30 ,506124 ,4555116 ),
('10:00-11:00','Bonus' ,1 ,30 ,0 ,0 ),
('10:00-11:00','Billed' ,1 ,30 ,109739 ,987651 ),
('10:00-11:00','Billed' ,1 ,30 ,109739 ,987651 ),
('10:00-11:00','Not Billed' ,1 ,30 ,98021 ,882189 ),
('09:00-10:00','Bonus' ,2 ,30 ,0 ,0 ),
('09:00-10:00','Billed' ,2 ,30 ,288947 ,2600523 ),
('09:00-10:00','Billed' ,2 ,30 ,288947 ,2600523 ),
('09:00-10:00','Not Billed' ,2 ,30 ,64669 ,582021 ),
('10:00-11:00','Bonus' ,2 ,30 ,0 ,0 ),
('10:00-11:00','Billed' ,2 ,30 ,48738 ,438642 ),
('10:00-11:00','Not Billed' ,2 ,30 ,269969 ,2429721 )

查询

SELECT *
FROM (SELECT TimeRange,
TYPE,
DATA,
left(DateName( month , DateAdd( month , month , 0 ) - 1 ),3) + ' '
+ COLUMN_NAME AS PIV_COL
FROM Yourtable
CROSS APPLY (VALUES ('ActionDuration',ActionDuration),
('GrossValue',GrossValue),
('NetValue',NetValue)) CS(COLUMN_NAME, DATA)) a
PIVOT (sum(DATA)
FOR PIV_COL IN([Jan ActionDuration],
[Jan GrossValue],
[Jan NetValue],
[Feb ActionDuration],
[Feb GrossValue],
[Feb NetValue])) PV

结果

TimeRange   TYPE        Jan ActionDuration  Jan GrossValue  Jan NetValue    Feb ActionDuration  Feb GrossValue  Feb NetValue
----------- ----------- ------------------ -------------- ------------ ------------------ -------------- -------------
09:00-10:00 Billed 30 77982 701838 60 577894 5201046
10:00-11:00 Billed 60 219478 1975302 30 48738 438642
09:00-10:00 Bonus 60 0 0 30 0 0
10:00-11:00 Bonus 30 0 0 30 0 0
09:00-10:00 Not Billed 30 506124 4555116 30 64669 582021
10:00-11:00 Not Billed 30 98021 882189 30 269969 2429721

关于sql-server - 对多列进行透视 (T-SQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31855778/

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