2017-03-03 69 views
-4

我想用1个电话返回所有的ID(工作的首位,如果没有工作,然后回家。或空电话)如何写一个Oracle查询

TALBE 1

ID Name 
01  ab 
02  cd 
03  ef 

表2

ID phone type 
01 1111 work 
01 1234 Home 
02 2345 home 
+0

您期望的输出是什么? –

+0

到目前为止,你有什么尝试?显示一些努力会很大 – Aleksej

+0

左加入太多次 – xyray

回答

0

就像这样......注意在子查询中使用ROW_NUMBER()来按电话类型优先顺序排列行,并使用CASE表达式来分配这些优先级。 rn也处于外连接状态;它必须在外连接的ON子句中,并且而不是WHERE子句中(将其放在WHERE子句中将撤销连接的字符)。

如果有人想使用它,我会包含CREATE TABLE声明。

注 - OP在输入中有'home''Home';这说明了为什么电话类型应存储在单独的小表中,并且table2应指向该小表,而不允许在type列中使用自由文本。

create table table1 (id, name) as 
    select 01, 'ab' from dual union all 
    select 02, 'cd' from dual union all 
    select 03, 'ef' from dual; 

create table table2 (id, phone, type) as 
    select 01, 1111, 'work' from dual union all 
    select 01, 1234, 'home' from dual union all 
    select 02, 2345, 'home' from dual; 

select t1.id, t1.name, sq.phone, sq.type 
from table1 t1 left outer join 
     (select id, phone, type, 
       row_number() over (partition by id 
        order by case type when 'work' then 0 
            when 'home' then 1 end) as rn 
     from table2 
     ) sq 
     on t1.id = sq.id and sq.rn = 1 
; 

ID NAME PHONE TYPE 
-- ---- ----- ---- 
1 ab 1111 work 
2 cd 2345 home 
3 ef  
+0

按预期工作,谢谢 – xyray

0

你可以使用左对表2和情况下加入两次当

select t1.id, t1.name, case when tb.phone is not null then tb.phone 
          when ta.phone is not null then ta.phone 
          else null 
         end phone 
from table1 t1 
left join table2 ta on t1.id = ta.id and ta.type = 'work' 
left join table2 tb on t1.id= tb.id and tb.type = 'Home' 
+0

这似乎效率很低 - 如果有五种电话类型,你需要加入表2的五份副本吗?最好先处理表2。 – mathguy

+0

其实我确实有超过20种类型定义在表2中 – xyray