首页 > 解决方案 > 获取不带 null 的不同值

问题描述

我有一张这样的桌子;

--Table_Name--
A   |  B    | C
-----------------
A1    NULL    NULL   
A1    NULL    NULL    
A2    NULL    NULL    
NULL  B1      NULL    
NULL  B2      NULL    
NULL  B3      NULL    
NULL  NULL    C1 

我想变成这样;

--Table_Name--
A   |  B    | C
-----------------
A1    B1      C1    
A2    B2      NULL    
NULL  B3      NULL

我该怎么做?

标签: sqloracle

解决方案


这是一个选项:

  • 样本数据来自第 1 - 9 行
  • 以下 CTE(第 11 - 13 行)从每列中获取排名不同的非空值
  • 最终查询(从第 15 行开始)通过在排名值上外部连接先前的 CTE 来返回所需的结果

SQL> with test (a, b, c) as
  2  (select 'A1', null, null from dual union all
  3   select 'A1', null, null from dual union all
  4   select 'A2', null, null from dual union all
  5   select null, 'B1', null from dual union all
  6   select null, 'B2', null from dual union all
  7   select null, 'B3', null from dual union all
  8   select null, null, 'C1' from dual
  9  ),
 10  --
 11  ta as (select distinct a, dense_rank() over (order by a) rn from test where a is not null),
 12  tb as (select distinct b, dense_rank() over (order by b) rn from test where b is not null),
 13  tc as (select distinct c, dense_rank() over (order by c) rn from test where c is not null)
 14  --
 15  select ta.a, tb.b, tc.c
 16  from ta full outer join tb on ta.rn = tb.rn
 17          full outer join tc on ta.rn = tc.rn
 18  order by a, b, c
 19  /

A  B  C
-- -- --
A1 B1 C1
A2 B2
   B3

SQL>

推荐阅读