【问题标题】:NULL handling in a least() function in Postgres/SQLPostgres/SQL 中最小()函数中的 NULL 处理
【发布时间】:2019-06-05 00:47:30
【问题描述】:

我希望查询返回两列中最少的一个。但是,如果 col1 和 col2 都为 NULL,则返回 NULL。我已经尝试过 coalesce() 和 nvl() 但是当 col1 和 col2 都为 NULL 时,两者都不处理这种情况。

对于 col1 = 3 和 col = 2:

select least(coalesce(3, 1000000), coalesce(2, 1000000))

这行得通,输出为 2。

这也适用于 col1 = 3 和 col2 = NULL:

select least(coalesce(3, 1000000), coalesce(NULL, 1000000))

但是,当 col1 = NULL 和 col2 = NULL 时,这不起作用

select least(coalesce(null, 1000000), coalesce(null, 1000000))

这给了我 1000000 而不是 null。 我该如何解释这种情况?

【问题讨论】:

  • 我真的不明白这个问题,如果两个参数都为空,至少会返回空。您似乎在这里比较的不仅仅是两列。能否提供样表、样例数据和预期结果?
  • 我同意 Jeremy 你的问题令人困惑,因为:least(null, null) 返回null

标签: sql postgresql null


【解决方案1】:

这个问题有点不清楚。我相信您正在尝试比较表格的两列。 Null 没有任何价值。所以当你在least()中使用它时,总是返回非空值,除非所有比较的值都是空的。因此,您可以将 0 替换为 null,如下所示。

select least(coalesce(0, value_1), coalesce(0, value_2));

【讨论】:

  • Hana, select least(coalesce(null, 1000000), coalesce(null, 1000000)) 不会返回 null,因为 coalesce 选择了第一个非 null 值。合并(null, 1000000) -> 1000000. and least(1000000, 1000000) -> 1000000
【解决方案2】:

您也可以使用 case 语句比较两列。

  CREATE TABLE emp_data (
Value1 int , 
value2 int
);

insert into emp_data (value1, value2) values (100, 200), (200,200), (300,150) 

Select case when value1 > value2 then value2
when value1 < value2 then value1  else null end as Comparison, value1, value2
from emp_data

输出:

Comparison Value1 value2 
     100         100    200
                 200    200
     150         300    150

这是小提琴:

https://dbfiddle.uk/?rdbms=postgres_10&fiddle=fbd19a9bbc6563d700495fa487888606

【讨论】:

  • 感谢您的回答!但是结果应该为空。这个例子并不能说明我认为的原因
  • @Hana 它确实给出了空值,我已经用一些示例数据更新了 fiddle 和 case 语句。
【解决方案3】:

您可以使用横向连接:

select t.*, x.least_val
from (values (2, 3)) t(col1, col2) cross join lateral
     (select min(col) as least_val
      from (values (t.col1), (t.col2)) v(col)
     ) x;

您似乎想要min() 的语义,所以这正是min()

如果你真的想使用least()和一个“神奇”的值,你可以使用nullif()

select nullif(least(coalesce(3, 1000000), coalesce(NULL, 1000000)), 1000000)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多