将行转换为Sql Server中的列

时间:2013-11-11 13:10:59

标签: sql sql-server pivot

我有这种格式的表格

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

预期的OP

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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