簡體   English   中英

Oracle - 每列的不同值(非不同計數)

[英]Oracle - Distinct values of each column(Not distinct count)

我需要在表的每一列中獲取不同的值。 例如:

Table1
Info1    info2   info3 
A         D       F
B         D       G 
B         E       H
                  I

我想要的結果是

Table1
Info1    info2   info3 
A         D       F
B         E       G 
                  H
                  I

此查詢在不匹配的地方返回 null。 有沒有其他選擇

Select A.Info1,B.Info2,C.Info3 from 
(Select distinct Info1 from table1) A full outer join
(Select distinct Info2 from table1) B on A.info1=B.Info2 full outer join
(Select distinct Info3 from table1) C on A.info1=C.Info3

您可以使用ROW_NUMBER來生成一個可以執行JOIN的字段:

select info1, info2, info3
from (
  select info1, row_number over (order by info1) as rn
  from (Select distinct Info1 from table1) t1) x1
full outer join (
  select info2, row_number over (order by info2) as rn
  from (Select distinct Info2 from table1) t2
) x2 on x1.rn = x2.rn
full outer join (
  select info3, row_number over (order by info3) as rn
  from (Select distinct Info3 from table1) t3
) x3 on x2.rn = x3.rn

我不確定這是否是最好的選擇。 但是其他答案並沒有完全達到預期的結果。 下面的查詢做了

select Info1,Info2,Info3 from 
(Select rownum as rA,Info1 from (select distinct Info1 from Tabl1 order by Info1)) A full outer join
(Select rownum as rB,Info2 from (select distinct Info2 from Tabl1 order by Info2)) B  on A.rA=B.rB full outer join
(Select rownum as rC,Info3 from (select distinct Info3 from Tabl1 order by Info3)) C on A.rA=C.rC
order by A.rA;

這里有一個問題,第一行應該有最大數量的唯一值,以便輸出不會因為不匹配而添加新行。

WITH sample1 
     AS (SELECT LEVEL lev 
         FROM   dual 
         CONNECT BY LEVEL < 10), 
     sample2 
     AS (SELECT Ascii('a') col 
         FROM   dual), 
     s3 
     AS (SELECT Trunc(dbms_random.Value(1, lev))            c1, 
                Chr(Trunc(dbms_random.Value(1, lev)) + col) c2, 
                'x' 
                || Trunc(dbms_random.Value(1, lev))         c3 
         FROM   sample1, 
                sample2), 
     s4 
     AS (SELECT c1, 
                c2, 
                c3, 
                Dense_rank() 
                  over ( 
                    PARTITION BY 1 
                    ORDER BY c1) d1, 
                Dense_rank() 
                  over ( 
                    PARTITION BY 1 
                    ORDER BY c2) d2, 
                Dense_rank() 
                  over ( 
                    PARTITION BY 1 
                    ORDER BY c3) d3 
         FROM   s3) 
SELECT DISTINCT l1.c1, 
                l2.c2, 
                l3.c3 
FROM   s4 l1 
       full outer join s4 l2 
                    ON l1.d1 = l2.d2 
       full outer join s4 l3 
                    ON l3.d3 = l1.d1 
ORDER  BY 1, 
          2, 
          3 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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