簡體   English   中英

Oracle 分貝。 如何獲取同一表的幾乎任意數量的列的唯一值的結果集

[英]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

我已經嘗試過的:

  1. 只有在有 2 到 3 列的情況下,聯合似乎才可行,但事實並非如此。
  2. 我找到了一個支點/反支點,但我並沒有真正掌握它。
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 ,則可以使用unpivotinclude 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM