我有2个表Customer&Company
公司
COMP_ID | COMP_NAME
1 | Google
2 | Facebook
Run Code Online (Sandbox Code Playgroud)
顾客
CUST_ID | COMP_ID | CUST_NAME
1 | 1 | John
2 | 2 | NULL
3 | 2 | Rob
Run Code Online (Sandbox Code Playgroud)
我想写一个查询显示CUST_NAME为CONTACT但如果CUST_NAME是NULL,则显示COMP_NAME为CONTACT
用途COALESCE:
select cs.cust_id, coalesce(cs.cust_name, co.comp_name) contact
from customer cs
inner join company co
on cs.comp_id = co.comp_id;
Run Code Online (Sandbox Code Playgroud)
如果cust_name中有空字符串,请执行以下操作:
select cs.cust_id, coalesce(nullif(cs.cust_name,''), co.comp_name) contact
from t_customer cs
inner join t_company co
on cs.comp_id = co.comp_id;
Run Code Online (Sandbox Code Playgroud)