我想用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
我想用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
就像这样......注意在子查询中使用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
按预期工作,谢谢 – xyray
你可以使用左对表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'
您期望的输出是什么? –
到目前为止,你有什么尝试?显示一些努力会很大 – Aleksej
左加入太多次 – xyray