需要帮助从Oracle表中获取价值

时间:2014-10-30 20:20:56

标签: sql oracle

我有2张桌子

表1

Name      City
--------------------
Deep      Delhi
Manu      Atlanta
Raju      PanamaCity

表2

City
-----
Delhi 

我想添加另一个名为" Country"在结果中所以最终的结果就像

Name      City          Country
-------------------------------
Deep      Delhi         Known
Manu      Atlanta       Unknown
Raju      PanamaCity    Unknown

因此,如果第一个表的city列的值是匹配的,则新列的值应该具有"已知"

1 个答案:

答案 0 :(得分:0)

阅读Joins和案例陈述

SELECT t1.name, 
  t2.city, 
  case t2.city is NULL then 'Unknown' else 'Known' end as Country
FROM table1 t1
LEFT JOIN table2 t2
 on t1.city = t2.city

样机:

Select t1.name, 
  t1.city, 
  case when t2.city is NULL then 'Unknown' else 'Known' end as Country 
FROM (
  select 'Deep' as Name, 'Dehli' as city from dual UNION
  select 'Manu' as Name, 'Atlanta' as city from dual UNION
  select 'Raju' as Name, 'PanamaCity' as city from dual) t1
LEFT JOIN 
(select 'Dehli' as city from dual) 
  t2
  on t1.city=t2.city

results in:
Name    City        Country
Deep    Dehli       Known
Manu    Atlanta     Unknown
Raju    PanamaCity  Unknown