我如何在SQL中执行此操作:
SELECT CLIENT, PAYMENT_CODE FROM PAYMENTS_TABLE
If PAYMENT_CODE = 1, SELECT other data from table_1
Else, SELECT other data from table_2
我想要的结果是:
| Client | Payment Code = 1 | Address from table_1 | Phone from table_1 | ...
或
| Client | Payment Code 1 | Address from table_2 | Phone from table_2 | ...
提前致谢!
答案 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