[英]Oracle db. How to get a result set of unique values of pretty much arbitrary amount of columns of the same table
Having this column structure具有这种列结构
Id, col_1, col_2, col_3
1 A A B
2 B B B
3 C C D
Is it possible to get one-column output with unique values?是否可以获得具有唯一值的一列 output?
res_column
A
B
C
D
What I've already tried:我已经尝试过的:
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
If you must handle null
also, you can do so with the include nulls
option to unpivot
.如果您还必须处理null
,则可以使用unpivot
的include nulls
nulls 选项来处理。 Without this option, the query above will still work - it will just ignore (discard, exclude) all null
from the unpivoted columns.如果没有这个选项,上面的查询仍然有效——它只会忽略(丢弃、排除)来自未透视列的所有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)
Note that the last result has five rows, not four;请注意,最后一个结果有五行,而不是四行; the last value is null
, which is invisible, but if you run the query in an editor that shows you the number of rows (or if you use an option to show null
as <null>
or such), then you will see it.最后一个值是null
,这是不可见的,但是如果您在显示行数的编辑器中运行查询(或者如果您使用选项将null
显示为<null>
等),那么您将看到它。
NOTE: You can't make this "generic" in plain SQL;注意:您不能在普通 SQL 中将此“通用”; the number of columns to unpivot, and their names, must be hard-coded in the query.要取消透视的列数及其名称必须在查询中进行硬编码。 If you need a "generic" solution you will need to use dynamic SQL;如果您需要“通用”解决方案,则需要使用动态 SQL; that is a much more advanced topic, and certainly not appropriate if you don't even grasp static unpivot
yet.这是一个更高级的主题,如果您甚至还没有掌握 static unpivot
,那肯定是不合适的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.