![](/img/trans.png)
[英]SQL select single distinct values from multiple columns (not combined values)
[英]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.