2014-03-05 75 views
0

列我有兩個表:現在的SQL Server 2008:轉換行到

CREATE TABLE #A (id int, cond_id int) 
INSERT INTO #A (id, cond_id) 
VALUES (101,20), 
     (101,22), 
     (101,24), 
     (102,23), 
     (102,22) 

,每個ID可以有4個cond_ids最大。我想填充表#B,以便有一個id,並且根據cond_id升序將所有cond_ids填充到一行中作爲一行。 類似於id 102,cond_id 22進入cond_id並且23進入cond_id2。

create table #B (id int, cond_id1 int, cond_id2 int, cond_id3 int, cond_id4 int) 

期望的結果:

表#B

id cond_id1 cond_id2 cond_id3 cond_id4 
101 20  22  24  null 
102 22  23  null  null 

提前感謝!

+2

您是否嘗試過谷歌有關T-SQL –

+0

甚至看相關欄這個職位的合適的PIVOT子句。 –

+0

我找不到任何東西。 – user3381370

回答

0

因爲你知道的最大列數,一個選擇是使用row_numbermaxcase

with cte as (
    select row_number() over (partition by id order by cond_id) rn, id, cond_id 
    from a) 
select id, 
    max(case when rn = 1 then cond_id end) cond_id1, 
    max(case when rn = 2 then cond_id end) cond_id2, 
    max(case when rn = 3 then cond_id end) cond_id3, 
    max(case when rn = 4 then cond_id end) cond_id4 
from cte 
group by id 

或者你可以看看透視:

select id, [1] cond_id1, [2] cond_id2, [3] cond_id3, [4] cond_id4 
from 
    (select row_number() over (partition by id order by cond_id) rn, id, cond_id 
    from a) t 
pivot 
(
    max(cond_id) 
    for rn in ([1], [2], [3], [4]) 
) p