Tsql - 每2条记录的数据透视

时间:2014-06-23 19:55:59

标签: sql-server-2008 tsql pivot

DATA

DECLARE @temp TABLE([Group] int,GroupOrder   int,Response int)
INSERT INTO @temp VALUES (1,1,1)
INSERT INTO @temp VALUES (1,2,1)
INSERT INTO @temp VALUES (2,1,1)
INSERT INTO @temp VALUES (2,2,1)
INSERT INTO @temp VALUES (2,3,2)
INSERT INTO @temp VALUES (2,4,1)

Group GroupOrder    Response
1     1           1
1     2           1
2     1           1
2     2           1
2     3           2
2     4           1

关于上述数据,该组按逻辑定义了Group,这意味着我有2个groupIds的数据,即1和2响应是我需要以这样一种方式进行转换,即响应的第一个值转到第一列并且第二个值转到每个组的第二列,并且按组顺序定义,预期结果为:

Group  Response Newcol
1         1        1
2         1        1
2         2        1

Response的第一个值应该转到Response Column,下一个值应该转到Newcol转移到该组的下一个记录(如果存在),同样的逻辑应该继续跟随。

我试过ROW_NUMBER()和Pivot,但我还没有成功。

1 个答案:

答案 0 :(得分:1)

DECLARE @temp TABLE([Group] int,GroupOrder   int,Response int)
INSERT INTO @temp VALUES (1,1,1)
INSERT INTO @temp VALUES (1,2,1)
INSERT INTO @temp VALUES (2,1,1)
INSERT INTO @temp VALUES (2,2,1)
INSERT INTO @temp VALUES (2,3,2)
INSERT INTO @temp VALUES (2,4,1)
INSERT INTO @temp VALUES (3,1,5)
INSERT INTO @temp VALUES (4,1,2)
INSERT INTO @temp VALUES (4,2,1)



select [Group], [1] as Response , [0] as NewCol 
from 
(
    select t.[group], 
            response, 
            GroupOrder%2 as pivotcol, 
            case when round(cast(grouporder as float)/2,0) <> cast(grouporder as float)/2 
                 then grouporder 
                 else grouporder-1 
            end as GG
    from @temp t
) dat
pivot(max(response) for pivotcol in ([1],[0])) pvt
order by [group]

结果:

Group       Response    NewCol
----------- ----------- -----------
1           1           1
2           1           1
2           2           1
3           5           NULL
4           2           1