查询以在SQL Server中将列转换为行

时间:2019-05-20 09:41:10

标签: sql sql-server database pivot unpivot

需要将此列转换为行

select okeydata
 from [elo].[dbo].[objkeys] 
 where parentid 
 in 
  ( select parentid from
   [elo].[dbo].[objekte] inner join [elo].[dbo].[objkeys] 
   on objid = parentid and objmask like 26 and okeydata like 1 )

原始输出

okeydata  
1
a
a@a.com
london

需要查询

okeydata  
1  a a@a.com london

1 个答案:

答案 0 :(得分:2)

如果需要四列,则可以使用row_number()pivot

select max(case when seqnum = 1 then okeydata end) as col_1,
       max(case when seqnum = 2 then okeydata end) as col_2,
       max(case when seqnum = 3 then okeydata end) as col_3,
       max(case when seqnum = 4 then okeydata end) as col_4
from (select okeydata,
             row_number() over (order by (select null)) as seqnum
      from [elo].[dbo].[objkeys] 
      where parentid in (select parentid
                         from [elo].[dbo].[objekte] inner join
                              [elo].[dbo].[objkeys] 
                               on objid = parentid 
                         where objmask like 26 and okeydata like 1 
                        )
     ) o;