簡體   English   中英

如何從 oracle sql 的單行中的多列中獲取不同的值

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

我有一排這樣的數據

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

output 應該是:

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

我需要從列中獲取不同的值並刪除存在的空值。

如果, first_cd...sixth_cd 是同一行上的列。 1 AB null C C D are the values Anyway to do in this in oracle sql

這是使用橫向連接的好地方:

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;

注意:這會將多余的值返回為NULL ,這似乎更符合您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM