在 CASE 中比较字符串
Comparing strings within CASE
我有一个 table 和 character varying
字段,就像这样 -
Bill Render Refer Supervise
1194772160
1538359872
1194772160
1104026103
1104026103
1831124015
1740237197 1740237197 1740237197
为什么下面的查询返回空字符串 -
SELECT
CASE
WHEN render != bill THEN render
END AS renderUnique
如果要比较空值是否相等,请使用 IS [NOT] DISTINCT FROM
:
SELECT CASE
WHEN render IS DISTINCT FROM bill THEN render
END AS renderUnique
请注意,x IS DISTINCT FROM y
大致表示 x 与 y 不同。真相 table 应该有帮助:
| x | y | x distinct from y | x not distinct from y |
|------|------|-------------------|-----------------------|
| 1 | 1 | f | t |
| 1 | NULL | t | f |
| NULL | 1 | t | f |
| NULL | NULL | f | t |
| 1 | 2 | t | f |
由于所有行都包含 null
列 bill
比较:
render != bill
相当于:
render != null
其中returnsnull
,所以不是true
和case
语句returnsnull
.
您可以将其更改为:
select
(CASE WHEN coalesce(render, '') != coalesce(bill, '') THEN render END) as renderUnique
我有一个 table 和 character varying
字段,就像这样 -
Bill Render Refer Supervise
1194772160
1538359872
1194772160
1104026103
1104026103
1831124015
1740237197 1740237197 1740237197
为什么下面的查询返回空字符串 -
SELECT
CASE
WHEN render != bill THEN render
END AS renderUnique
如果要比较空值是否相等,请使用 IS [NOT] DISTINCT FROM
:
SELECT CASE
WHEN render IS DISTINCT FROM bill THEN render
END AS renderUnique
请注意,x IS DISTINCT FROM y
大致表示 x 与 y 不同。真相 table 应该有帮助:
| x | y | x distinct from y | x not distinct from y |
|------|------|-------------------|-----------------------|
| 1 | 1 | f | t |
| 1 | NULL | t | f |
| NULL | 1 | t | f |
| NULL | NULL | f | t |
| 1 | 2 | t | f |
由于所有行都包含 null
列 bill
比较:
render != bill
相当于:
render != null
其中returnsnull
,所以不是true
和case
语句returnsnull
.
您可以将其更改为:
select
(CASE WHEN coalesce(render, '') != coalesce(bill, '') THEN render END) as renderUnique