如何将第一行中的第二行显示为列值

时间:2018-06-18 10:05:55

标签: sql sql-server

我有一个名为Test的SQL表。其中只有两行数据如下所示: Select * from Test Result

注意 只有两个音符可以是1或2,而Name可以是任何音符。注意顺序不是顺序可以插入仅与注1相关的名称或仅与注2相关

我需要结果如下图所示:

Expected result

注意 如果表中只有Note值1记录,则ID2,Name2和Note2始终应为null。

有人可以帮我用SQL查询来实现这个目标吗?

提前致谢!

3 个答案:

答案 0 :(得分:1)

试试这个

 select a.Id as Id1, a.Name as Name1, a.Note as Note1,
    b.Id as Id2, b.Name as Name2, b.Note as Note2  
    from Test as a
    left join Test as b on b.Id = 2
    where a.Id = 1

编辑为以下评论

 select a.Id as Id1, a.Name as Name1, a.Note as Note1,
    b.Id as Id2, b.Name as Name2, b.Note as Note2  
    from Test as a
    left join Test as b on b.Id = a.Id+1
    where a.Id % 2 ! = 0

答案 1 :(得分:1)

如果您想要 singe 行,那么您可以执行以下操作:

select 
      max(case when seq = 1 then id end) as id1, 
      max(case when seq = 1 then Name end) as Name1, 
      max(case when seq = 1 then Note end) as Note1, 
      max(case when seq = 2 then id end) as id2, 
      max(case when seq = 2 then Name end) as Name2,
      max(case when seq = 2 then Note end) as Note2
from (select *, 1+(row_number() over (order by id)-1) % 2 as seq
      from test
     ) t
group by (id-seq);

答案 2 :(得分:1)

您可以构建只包含note = 1note = 2的记录的子集,其中row_number()包括FULL JOINrow_number()

SELECT x.id id1,
       x.name name1,
       x.note note1,
       y.id id2,
       y.name name2,
       y.note note2
       FROM (SELECT t.id,
                    t.name,
                    t.note,
                    row_number() OVER (ORDER BY t.id) row#
                    FROM test t
                    WHERE t.note = 1) x
            FULL JOIN (SELECT t.id,
                              t.name,
                              t.note,
                              row_number() OVER (ORDER BY t.id) row#
                              FROM test t
                              WHERE t.note = 2) y
                      ON x.row# = y.row#;