SQL 当 a 为 NULL 时的情况

SQL CASE WHEN a is NULL

我有 3 列都包含电子邮件地址

email
alt_email
main_email

我想在电子邮件为空时处理 alt_email 当 alt_email 为 null 时发送电子邮件,当两者都为 null 时 main_email 结束为 all_emails.

我没有得到正确答案,因为 all_emails 的总数比所有客户总数少 90%。

TIA

Select CASE WHEN (email != '') THEN email WHEN (alt_email != '') THEN alt_email ELSE main_email END AS emaiId From table

SELECT
CASE
    WHEN email IS NULL AND alt_email IS NULL THEN main_email
    WHEN email IS NULL AND alt_email IS NOT NULL THEN alt_email
    WHEN alt_email IS NULL AND email IS NOT NULL THEN email
    ELSE email
END AS all_emails
FROM some_table;

正如@sparky 提到的,这是 COALESCE 的工作:

SELECT COALESCE(email, alt_email, main_email) AS all_email FROM ...

它按顺序从提到的列中获取第一个 non-null 值。

参见 SqlServer 的文档,但同样的语法也适用于其他 DBMS。