【问题标题】:use Oracle DECODE function select phone_number with the same column in two tables使用 Oracle DECODE 函数在两个表中选择具有相同列的 phone_number
【发布时间】:2017-06-16 04:19:32
【问题描述】:

表格:

table_a

user_id | phone_number|state|...|

table_b

user_id | phone_number | ...|

条件:

  1. 必须使用Oracle DECODE 函数来执行SQL 语句。
  2. 如果table_b.phone_number不为空,使用table_b.phone_number,否则如果table_a.state=3使用table_a.phone_number
  3. table_atable_buser_id 加入

结果:

选择所有user_id,phone_number映射结果like

user_id | phone_number

【问题讨论】:

  • 到目前为止你尝试过什么?看起来像家庭作业...

标签: sql oracle decode


【解决方案1】:

为什么必须使用DECODE()?它不适合实现您的要求。 CASE() 是正确的解决方案。

select a.user_id
       , case 
             -- condition 1
             when b.phone_number is not null then b.phone_number
             -- condition 2
             when a.state = 3 then a.phone_number
             -- conditions not met
             else 'no phone'
          end as phone_number
from a 
     join b on a.user_id = b.user_id  

这可以用decode() 来完成,但这有多笨重?

 decode(b.phone_number
         , null
         , decode(a.state
                   , 3
                   , a.phone_number
                   , 'no phone')
         ,  b.phone_number) as phone_number

【讨论】:

  • 看起来像一个家庭作业问题。这就是为什么DECODE 是强制性的。
  • @Nitish - 你可能是对的。这个网站到处都是学生,他们要求解决错误的作业:(
【解决方案2】:

试试这个..

select a.user_id,
      decode(b.phone_number,
             null,
             decode(a.state,
                    3,
                     a.phone_number),
      b.phone_number) phoneNumber 
     from table_a a,
          table_b b 
where a.user_id=b.user_id(+)

【讨论】:

  • 为什么 (+) 在 a.user_id=b.user_id(+)
  • 没有任何问题表明 LEFT JOIN 是必要的。
  • 这个解决方案也是错误的,因为它将 A.PHONE_NUMBER 优先于 B.PHONE_NUMBER,而问题明确指出如果存在 B,则应使用它
【解决方案3】:

将 NVL 与 DECODE 结合使用:

select a.user_id, nvl(b.phone_number, decode(a.state,3,a.phone_number,null)) phone_no from table_a a left join table_b b on a.user_id = b.user_id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多