sql server - Pivot Operation in SQL Query -


i working on table has data this-- sorry formatting new here

cola  type    name    email  -----------------------    1     type1  john     yyyy@m   1     type2  emily    xxx@m   2     type2  richard  ooo@m   3     type1  rebecca  pppp@m   3     type2  pumpkin   nnnn@m   

i want have output based on type column

col1 type1name type1email type2name type2email  -------------------------    1    john      yyyy@m      emily    xxx@m    2    null      null        richard  ooo@m   3    rebecca   pppp@m      pumpkin    nnnn@m     

i tried 2 cte's pivots , joining them did not results suggestions

joining pivot worked me, , got result required,

select name.col1 ,name.type1name ,email.type1email ,name.type2name ,email.type2email (     select cola col1         ,type1 type1name         ,type2 type2name     (         select cola             ,name             ,type         #table_name --your table name here         )     pivot(max(name) type in (                 [type1]                 ,[type2]                 )) pvt     ) name inner join (     select cola col1         ,type1 type1email         ,type2 type2email     (         select cola             ,email             ,type         #table_name --your table name here         )     pivot(max(email) type in (                 [type1]                 ,[type2]                 )) pvt     ) email on name.col1 = email.col1 

the result below,

col1    type1name   type1email  type2name   type2email 1       john        yyyy@m      emily       xxx@m 2       null        null        richard     ooo@m 3       rebecca     pppp@m      pumpkin     nnnn@m 

Comments