【问题标题】:Tsql - Pivot data for every 2 recordsTsql - 每 2 条记录的数据透视
【发布时间】:2014-06-24 07:03:29
【问题描述】:

数据

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 按逻辑定义 Group,这意味着我有 2 个 groupId 的数据,即 1 和 2 响应是我需要以这样的方式旋转的响应的第一个值转到第一列第二个值进入每组的第二列,按照组顺序定义,预期结果是:

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

Response 的第一个值应该进入 Response Column,下一个值应该进入 Newcol 移动到该组的下一条记录(如果存在),应该继续遵循相同的逻辑。

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

【问题讨论】:

  • 总是成对的吗?第 3 组可以有 1 行吗?
  • 一对永远存在

标签: sql-server-2008 tsql pivot


【解决方案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

【讨论】:

    猜你喜欢
    • 2014-08-10
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 2013-07-02
    • 2019-03-07
    相关资源
    最近更新 更多