我想基于代码列数据返回具有相同数据的多行。 我可以使用UNION ALL来实现。没有UNION ALL,有没有办法做到这一点。我有超过10列(S1,S2,.... S10)。在样本数据中,我仅提供了3列(S1,S2,S3)。
SELECT ID , NAME , S1 SCODE
FROM TBL1
WHERE S1 IS NOT NULL
UNION ALL
SELECT ID , NAME , S2 SCODE
FROM TBL1
WHERE S2 IS NOT NULL
实际表格:
ID NAME S1 S2 S3
1 T1 AA BB CC
2 T2 AA KK
预期结果:
ID NAME SCODE
1 T1 AA
1 T1 BB
1 T1 CC
2 T2 AA
2 T2 KK
答案 0 :(得分:0)
这里是一个选择:连接Sx
列,然后进行相反的操作-将它们拆分为行。
SQL> with test (id, name, s1, s2, s3) as
2 (select 1, 'T1', 'AA', 'BB', 'CC' from dual union all
3 select 2, 'T2', 'AA', null, 'KK' from dual
4 ),
5 temp as
6 (select id,
7 name,
8 s1 || decode(s1, null, null, ':') ||
9 s2 || decode(s2, null, null, ':') ||
10 s3 col
11 from test
12 )
13 select id,
14 name,
15 regexp_substr(col, '[^:]+', 1, column_value) scode
16 from temp join table(cast(multiset(select level from dual
17 connect by level<= regexp_count(col, ':') + 1
18 ) as sys.odcinumberlist)) on 1 = 1;
ID NA SCODE
---------- -- --------------------------------
1 T1 AA
1 T1 BB
1 T1 CC
2 T2 AA
2 T2 KK
SQL>
答案 1 :(得分:0)
尝试使用UNPIVOT
子句:
with
test (id, name, s1, s2, s3) as (
select 1, 'T1', 'AA', 'BB', 'CC' from dual union all
select 2, 'T2', 'AA', null, 'KK' from dual
)
select id, name, scode
from test
unpivot (scode for cols in (S1, S2, S3)) up;
输出:
| ID | NAME | SCODE |
+----+------+-------+
| 1 | T1 | AA |
| 1 | T1 | BB |
| 1 | T1 | CC |
| 2 | T2 | AA |
| 2 | T2 | KK |
使用rextester.com在线进行测试。