![](/img/trans.png)
[英]Oracle DB. How to get a running total from multiple columns on one record
[英]Oracle db. How to get a result set of unique values of pretty much arbitrary amount of columns of the same table
具有这种列结构
Id, col_1, col_2, col_3
1 A A B
2 B B B
3 C C D
是否可以获得具有唯一值的一列 output?
res_column
A
B
C
D
我已经尝试过的:
with
sample_inputs (id, col_1, col_2, col_3) as (
select 1, 'A', 'A', 'B' from dual union all
select 2, 'B', 'B', 'B' from dual union all
select 3, 'C', 'C', 'D' from dual
)
select distinct res_column
from sample_inputs
unpivot (res_column for col in (col_1, col_2, col_3))
order by res_column --- if needed
;
RES_COLUMN
----------
A
B
C
D
如果您还必须处理null
,则可以使用unpivot
的include nulls
nulls 选项来处理。 如果没有这个选项,上面的查询仍然有效——它只会忽略(丢弃、排除)来自未透视列的所有null
。
with
sample_inputs (id, col_1, col_2, col_3) as (
select 1, 'A' , 'A' , 'B' from dual union all
select 2, 'B' , 'B' , 'B' from dual union all
select 3, 'C' , 'C' , 'D' from dual union all
select 4, null, null, null from dual
)
select distinct res_column
from sample_inputs
unpivot include nulls (res_column for col in (col_1, col_2, col_3))
order by res_column --- if needed
;
RES_COLUMN
----------
A
B
C
D
(five rows selected)
请注意,最后一个结果有五行,而不是四行; 最后一个值是null
,这是不可见的,但是如果您在显示行数的编辑器中运行查询(或者如果您使用选项将null
显示为<null>
等),那么您将看到它。
注意:您不能在普通 SQL 中将此“通用”; 要取消透视的列数及其名称必须在查询中进行硬编码。 如果您需要“通用”解决方案,则需要使用动态 SQL; 这是一个更高级的主题,如果您甚至还没有掌握 static unpivot
,那肯定是不合适的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.