SQL - 如果满足某个条件,则从表中选择,否则从另一个条件中选择SELECT

时间:2014-10-09 15:40:26

标签: sql db2

我如何在SQL中执行此操作:

  1. SELECT CLIENT, PAYMENT_CODE FROM PAYMENTS_TABLE
  2. If PAYMENT_CODE = 1, SELECT other data from table_1
  3. Else, SELECT other data from table_2
  4. 我想要的结果是:

    | Client | Payment Code = 1 | Address from table_1 | Phone from table_1 | ...
    

    | Client | Payment Code  1 | Address from table_2 | Phone from table_2 | ...
    

    提前致谢!

3 个答案:

答案 0 :(得分:2)

虽然Rajesh的解决方案很好,但您也可以使用两个LEFT JOIN来完成;

SELECT pt.CLIENT, pt.PAYMENT_CODE, 
       COALESCE(t1.address, t2.address) address, 
       COALESCE(t1.phone,   t2.Phone)   phone
FROM PAYMENTS_TABLE pt
LEFT JOIN Table_1 t1 
  ON pt.client_code = t1.client_code AND pt.PAYMENT_CODE =  1
LEFT JOIN Table_2 t2 
  ON pt.client_code = t2.client_code AND pt.PAYMENT_CODE <> 1

编辑:根据对另一个答案的评论添加client_code作为链接条件。

答案 1 :(得分:1)

当payment_code = 1时,您需要使用UNION,一个SELECT查询来获取table_1中的详细信息;当payment_code不等于1时,需要使用另一个SELECT来获取table_2中的详细信息

SELECT CLIENT, PAYMENT_CODE, T1.Address, T1.Phone FROM PAYMENTS_TABLE
JOIN Table_1 T1
ON -- your condition
WHERE PAYMENT_CODE =1
UNION 
SELECT CLIENT, PAYMENT_CODE, T2.Address, T2.Phone FROM PAYMENTS_TABLE
JOIN Table_2 T2
ON -- your condition
WHERE PAYMENT_CODE <> 1

答案 2 :(得分:1)

您没有告诉我们table_1和table_2如何链接到payments_table,但这样的事情应该有效:

select p.client, 
       p.payment_code,
       case 
          when payment_code = 1 then t1.address
          else t2.address
       end as address,
       case 
          when payment_code = 1 then t1.phone
          else t2.phone
       end as phon
from payments_table p
   left join table_1 t1 on p.some_column = t1.some_column
   left join table_2 t2 on p.some_column = t2.come_column