2014-03-05 42 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