简体   繁体   中英

how to get distinct values from multiple columns in 1 single row in oracle sql

I have a row of data like this

id  first_cd    sec_cd  third_cd    fourth_cd   fifth_cd     sixth_cd
1   A           B           null        C           C            D
                    

output should be:

id  first_cd    sec_cd  third_cd    fourth_cd   fifth_cd     sixth_cd
1   A           B       C           D           D               D

I need to get distinct values from the columns and remove nulls where there are.

if, first_cd...sixth_cd are columns on the same row. 1 AB null C C D are the values Anyway to do in this in oracle sql

This is a good place to use lateral joins:

select t.*, x.*
from t cross join lateral
      (select max(case when seqnum = 1 then cd end) as cd1,
              max(case when seqnum = 2 then cd end) as cd2,
              max(case when seqnum = 3 then cd end) as cd3,
              max(case when seqnum = 4 then cd end) as cd4,
              max(case when seqnum = 5 then cd end) as cd5,
              max(case when seqnum = 6 then cd end) as cd6             
      from (select t.*, row_number() over (order by n) as seqnum
            from (select t.cd1 as cd, 1 as n from dual union all
                  select t.cd2, 2 from dual union all
                  select t.cd3, 3 from dual union all
                  select t.cd4, 4 from dual union all
                  select t.cd5, 5 from dual union all
                  select t.cd6, 6 from dual 
                 ) x
            where cd is not null
           ) x
      ) x;

Note: This returns the excess values as NULL , which seems more in line with your problem.

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