Oracle - 每列的不同值(非明显计数)

时间:2016-09-01 07:03:43

标签: sql oracle

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

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

3 个答案:

答案 0 :(得分:0)

您可以使用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

答案 1 :(得分:0)

我不确定这是不是最好的选择。但其他答案并没有完全符合预期的结果。下面的查询确实

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;

虽然这里有一个问题,第一行应该有最大数量的唯一值,这样输出就不会因为不匹配而添加新行。

答案 2 :(得分:0)

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