简体   繁体   中英

How to transpose distinct column values to column names and map other column values to each column name

I am using Oracle SQL to transpose a table to the output seen below. From my side, I tried doing pivots and joins, but the output doesnt seem to match. Any help on this would be much appreciated

Type | Name
-----+-----------
D    | Aamina
D    | Julia
D    | Priya
P    | Ashley
P    | Belvet
S    | Christeen
S    | Jane
S    | Jenny
A    | Eve
A    | Jennifer
A    | Ketty
A    | Samantha

Need this kind output...

D      | P      | S         | A
-------+--------+-----------+----------
Aamina | Ashley | Christeen | Eve
Julia  | Belvet | Jane      | Jennifer
Priya  | NULL   | Jenny     | Ketty
NULL   | NULL   | NULL      | Samantha

You can use conditional aggregation and row_number() :

select max(case when type = 'D' then name end) as d,
       max(case when type = 'P' then name end) as p,
       max(case when type = 'S' then name end) as s,
       max(case when type = 'A' then name end) as a       
from (select t.*,
             row_number() over (partition by type) as seqnum
      from t
     ) t
group by seqnum
order by seqnum;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM