我在学习合并时感到困惑,我是 sql 新手。
例子:
select case when value is null then 1
else value end as value
from table
和
select coalesce(value, 1)
from table
我在网上看到的教程里有这样的
select coalesce (arg_1, arg_2, arg_3)
如果我做
select coalesce(value, 1, 2)
我怎样才能显示返回值为 2?
最佳答案
您的第一个和第二个查询
将重现相同的结果,但您对Coalesce
概念的理解是错误的。
The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null.
所以这意味着它会返回第一个参数not null
,它不像case
语句那样有true
或假
让我们举个例子:
select coalesce(null, 1)
它将像您显示的查询一样返回 1
,或者
select coalesce(null, null, 1)
即使 arg_3
中的 1
也会返回 1
并且有 2 个值 not null
怎么样?
select coalesce(null, 1, 2)
它将返回 1
。为什么?就像在文档中所说的“返回它的第一个不为空的参数”所以当有 2 个值时 not null
第一个参数有 not null
值将得到返回
您可以查看此演示并尝试:
希望对你有帮助
关于sql - 结合大小写不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52959235/