SQL Server 2008:将行转换为列

时间:2014-03-05 00:40:53

标签: sql sql-server-2008 sql-update pivot

我有两张桌子:

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_ids将根据cond_id升序在列中填充为一行。 比如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

提前致谢!

1 个答案:

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

或者你可以看看Pivot:

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