I have 3 tables:
table1
:
id
111
222
333
444
table2
:
id ---- flag
111 ---- yes
222 ---- yes
444 ---- yes
table3
:
id ---- flag
111 ---- no
222 ---- yes
333 ---- yes
I want to create a new table that populates with 'yes' to '1' and 'no' or non-existent to '0', but only those records which have at least one 'no' or non-existent as such:
new table:
id ------- table2flag ----------- table3flag
111 ------- 1 ------------------- 0
333 -------- 0 ------------------- 1
444 -------- 1 ------------------- 0
Notice how there is no entry for 222 since they are both yes in both tables. How can I achieve this with Oracle sql?
答案 0 :(得分:1)
Do LEFT JOIN
's. Use coalesce
to return 'no' instead of null.
select t1.id, coalesce(t2.flag, 'no') table2flag, coalesce(t3.flag, 'no') table3flag
from table1 t1
left join table2 t2 on t1.id = t2.id
left join table3 t3 on t1.id = t3.id
Edit: To skip rows with same id existing in both table2 and table3, both with flag = true, simply add that condition in a WHERE
clause. Use case
to return 1 for yes, otherwise 0.
select t1.id,
case when t2.flag = 'yes' then 1 else 0 end as table2flag,
case when t3.flag = 'yes' then 1 else 0 end as table3flag
from table1 t1
left join table2 t2 on t1.id = t2.id
left join table3 t3 on t1.id = t3.id
where not (t2.flag = 'yes' and t3.flag = 'yes')
答案 1 :(得分:0)
试试这个
select table1.Id, DECODE (table2.flag, 'yes',1,0) flag1 ,DECODE (table3.flag, 'yes',1,0) flag2 from table1 left join table2
on table1.id = table2.id
left join table3 on table1.id = table3.id
WHERE NOT(DECODE (table2.flag, 'yes',1,0)=1 and DECODE (table3.flag, 'yes',1,0)=1)