0

need to convert this column to row

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 )

acutal output

okeydata  
1
a
a@a.com
london

need query to be

okeydata  
1  a a@a.com london
Pham X. Bach
  • 4,501
  • 2
  • 21
  • 33
  • What have you tried so far? What determines the order of those rows/columns? There are plenty of examples on how to pivot data on Stack Overflow; what was wrong with those examples? – Larnu May 20 '19 at 09:43
  • If you are on SQL Server 2017, look into `STRING_AGG`. – Matt May 20 '19 at 09:53
  • Possible duplicate of [SQL Server : Columns to Rows](https://stackoverflow.com/questions/18026236/sql-server-columns-to-rows) – Amira Bedhiafi May 20 '19 at 10:36

1 Answers1

2

If you want four columns, you can use row_number() or 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;
Gordon Linoff
  • 1,122,135
  • 50
  • 484
  • 624