在两行中写入两个非空值
writing two Non Null values in two rows
当 A 列和 B 列中存在非空值时,我正在寻找将一行中的值拆分为两行的有效方法
这是一种选择;合并两个集合,return 只有那些 cola
不为空的集合。
示例数据:
SQL> with test (cola, colb, colc) as
2 (select 1, null, 'AA' from dual union all
3 select 2, 6, 'BB' from dual union all
4 select 3, null, 'CC' from dual union all
5 select 4, null, 'DD' from dual union all
6 select 5, null, 'EE' from dual
7 ),
查询从这里开始:
8 temp as
9 (select cola, colc from test
10 union all
11 select colb, colc from test
12 )
13 select cola, colc
14 from temp
15 where cola is not null
16 order by colc, cola;
COLA COLC
---------- ----------
1 AA
2 BB
6 BB
3 CC
4 DD
5 EE
6 rows selected.
SQL>
您评论说“输入”是许多连接和嵌套查询的结果;没问题 - 只需将 复杂的 查询用作 CTE:
with test as
(your complicated query with joins and nested queries goes here),
temp as
the rest is copy/paste from above
你可以UNPIVOT
:
SELECT output, col3
FROM table_name
UNPIVOT (
output FOR key IN (cola, colb)
)
或者,将 table_name
替换为包含您的查询的 ()
方括号。
其中,对于示例数据:
其中,对于示例数据:
CREATE TABLE table_name (cola, colb, col3) AS
SELECT LEVEL, CASE LEVEL WHEN 2 THEN 6 END, CHR(64+LEVEL) || CHR(64 + LEVEL)
FROM DUAL
CONNECT BY LEVEL <= 5;
输出:
OUTPUT
COL3
1
AA
2
BB
6
BB
3
CC
4
DD
5
EE
db<>fiddle here
当 A 列和 B 列中存在非空值时,我正在寻找将一行中的值拆分为两行的有效方法
这是一种选择;合并两个集合,return 只有那些 cola
不为空的集合。
示例数据:
SQL> with test (cola, colb, colc) as
2 (select 1, null, 'AA' from dual union all
3 select 2, 6, 'BB' from dual union all
4 select 3, null, 'CC' from dual union all
5 select 4, null, 'DD' from dual union all
6 select 5, null, 'EE' from dual
7 ),
查询从这里开始:
8 temp as
9 (select cola, colc from test
10 union all
11 select colb, colc from test
12 )
13 select cola, colc
14 from temp
15 where cola is not null
16 order by colc, cola;
COLA COLC
---------- ----------
1 AA
2 BB
6 BB
3 CC
4 DD
5 EE
6 rows selected.
SQL>
您评论说“输入”是许多连接和嵌套查询的结果;没问题 - 只需将 复杂的 查询用作 CTE:
with test as
(your complicated query with joins and nested queries goes here),
temp as
the rest is copy/paste from above
你可以UNPIVOT
:
SELECT output, col3
FROM table_name
UNPIVOT (
output FOR key IN (cola, colb)
)
或者,将 table_name
替换为包含您的查询的 ()
方括号。
其中,对于示例数据:
其中,对于示例数据:
CREATE TABLE table_name (cola, colb, col3) AS
SELECT LEVEL, CASE LEVEL WHEN 2 THEN 6 END, CHR(64+LEVEL) || CHR(64 + LEVEL)
FROM DUAL
CONNECT BY LEVEL <= 5;
输出:
OUTPUT COL3 1 AA 2 BB 6 BB 3 CC 4 DD 5 EE
db<>fiddle here