我有一个这种格式的表格
+------+-------+--------+-----------+------------+
| WBID | State | Amount | SplitCode | SplitValue |
+------+-------+--------+-----------+------------+
| 1 | AP | 10 | W | 15 |
| 1 | AP | 10 | W | 25 |
| 1 | BC | 10 | W | 33 |
| 1 | BC | 10 | W | 57 |
| 2 | AP | 75 | W1 | 35 |
| 2 | AP | 75 | W2 | 35 |
+------+-------+--------+-----------+------------+
预期的操作
+------+-------+--------+----+----+----+----+
| WBID | State | Amount | W1 | W2 | W3 | W5 |
+------+-------+--------+----+----+----+----+
| 1 | AP | 10 | 5 | 5 | | |
| 1 | BC | 10 | | | 3 | 7 |
| 2 | AP | 75 | 35 | 35 | | |
+------+-------+--------+----+----+----+----+
请帮助如何使用 Pivot
编辑问题并输入详细格式 -
Drop Table #Temp
Create Table #Temp
(
WBID int,
WBNM Varchar(20),
State Varchar(2),
TotalAmount decimal(6,2),
SPlitCode Varchar(2),
SplitValue decimal(6,2)
)
Insert Into #Temp
Select 1,'PR1','CT',10,'W2',5
Union ALL
Select 1,'PR1','CT',10,'W3',5
Union ALL
Select 2,'PR1','CT',10,'W4',4
Union ALL
Select 2,'PR1','CT',10,'W5',6
Union ALL
Select 3,'PR1','CT',10,'W2',6
Union ALL
Select 3,'PR1','CT',10,'W4',4
Union ALL
Select 3,'PR1','NY',70,'W2',35
Union ALL
Select 3,'PR1','NY',70,'W5',35
Select distinct
WBID,
WBNM,
STate,
TOtalAMOUNT ,
W2,W3,w4,W5,W8
From #Temp
Pivot
(
sum(SplitValue ) for SplitCode in ( W2,W3,w4,W5,W8 )
) piv;