sql - 评估为空校正的列
问题描述
表格1:
ID email
A a@gmail.com
表 2:
ID email2 email3 email4
A a@gmail.com null ab@gmail.com
询问:
select T1.ID, T1.email,
case when T1.email<>T2.email2 then T2.email2 end email2,
case when T1.email<>T2.email3 and T2.email2<>T2.email3 then T2.email3 end email3,
case when T1.email<>T2.email4 and T2.email2<>T2.email4 and T2.email3<>T2.email4 then T2.email4 end email4
from t1
left join t2 on t1.id=t2.id
输出:
ID email email2 email3 email4
A a@gmail.com null null null
预期输出:
ID email email2 email3 email4
A a@gmail.com null null ab@gmail.com
看起来email4
评估为空,因为email3
它是空的。我想我明白为什么按照为什么 NULL = NULL 在 SQL server 中评估为 false,但是我有一种简单的方法可以避免这种情况发生吗?真正的查询要复杂得多,如果我isnull(value,'')
在 case 语句中的每个变量周围添加类似的东西以避免与空值进行比较,那可能会变得很多。
请注意,我无权更改ansi_nulls
设置等
解决方案
因为NULL
意味着
我不知道。
所以你可以尝试IS NULL
在每一CASE WHEN
列中添加检查
CREATE TABLE Table1(
ID VARCHAR(50),
email VARCHAR(50)
);
INSERT INTO Table1 VALUES ('A','a@gmail.com');
CREATE TABLE Table2(
ID VARCHAR(50),
email2 VARCHAR(50),
email3 VARCHAR(50),
email4 VARCHAR(50)
);
INSERT INTO Table2 VALUES ('A','a@gmail.com',null,'ab@gmail.com');
查询 1:
select T1.ID, T1.email,
case when T1.email<>T2.email2 then T2.email2 end email2,
case when T1.email<>T2.email3 and T2.email2<>T2.email3 then T2.email3 end email3,
case when (T1.email<>T2.email4 OR T1.email IS NULL) and
(T2.email2<>T2.email4 OR T2.email2 IS NULL) and
(T2.email3<>T2.email4 OR T2.email3 IS NULL) then T2.email4 end email4
from Table1 t1
left join Table2 t2 on t1.id=t2.id
结果:
| ID | email | email2 | email3 | email4 |
|----|-------------|--------|--------|--------------|
| A | a@gmail.com | (null) | (null) | ab@gmail.com |
推荐阅读
- pandas - 如何通过具有 NaN 值的多个(即所有可用的)属性对条目进行分组?
- c# - 当我得到 CompareTo() 时,如何按顺序在排序的 C# 列表中插入多个对象
- r - 在 R 中创建具有多个类别的单个变量
- java - 在定义的时间段后关闭活动
- objective-c - 调用方法时源文件中的目标 C 编辑器占位符
- excel-formula - 对同一列中的不同行数求和
- angular - ngx-scrollbar 不适用于 mat-dialog-content
- ios - 在一个屏幕中拥有一些 UITableViews 和一些 UICollectionViews
- c++ - 将一个类中创建的多地图数据传递给另一个类
- php - Laravel 在 PHPUnit 测试期间断言多个电子邮件收件人