-1

我有一个这种格式的表格

+------+-------+--------+-----------+------------+
| 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;
4

2 回答 2

2

我猜您正在寻找一种动态方法,以便您始终获得新的 Wx -splitcode 的新列。除了动态构建查询之外,我别无他法:

DECLARE @query  nvarchar(max)
DECLARE @cols   nvarchar(max)
SELECT @cols = STUFF((SELECT distinct ',' + QUOTENAME(SplitCode) 
              FROM CTE 
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')


SET @query = '
Select distinct 
  wbid, state, amount,'
  + @cols + '
From CTE
Pivot
(
  sum(SplitValue)
  for SplitCode  in ( ' + @cols + ' )
) piv;
'

EXECUTE(@query)
于 2013-11-11T13:57:15.727 回答
0

像这样的东西

select WBID, State, Amount, 
max(case when splitcode='W1' then splitvalue end) as w1,
max(case when splitcode='W2' then splitvalue end) as w2,
.
from table
group by  WBID, State, Amount
于 2013-11-11T13:15:06.123 回答