【问题标题】:Not equals when using CASE statement in SQL在 SQL 中使用 CASE 语句时不等于
【发布时间】:2015-06-25 23:19:58
【问题描述】:

在 postgresql 中,我有一个 case 语句,我需要添加一个“不等于”子句。

v1 等于v2 时,我想说1,当v1 不等于 v2 时,我想说2。

create table test (
v1      varchar(20),
v2      varchar(20)
);

insert into test values ('Albert','Al'),('Ben','Ben')

select case v1
when v2 then 1
    else 3
end 
from test

我尝试使用!=<>,但这似乎不起作用。

有谁知道如何在 SQL 的 case 语句中使用不等于?

【问题讨论】:

    标签: sql postgresql case


    【解决方案1】:

    首先,您从reading the documentation 开始。您会注意到 SQL case 函数采用以下两种形式之一:

    case {expression}
      when {value-1} then {result-1}
      ...
      when {value-N} then {result-N}
    [ else {default-result} ]
    end
    

    case
      when {boolean-condition-1} then {result-1}
      ...
      when {boolean-condition-N} then {result-N}
    [ else {default-result]
    end
    

    所以,你可以这样说

    select * ,
           case
             when v1  = v2                          then 1
             when v1 != v2                          then 2
             when v1 is     null and v2 is not null then 2
             when v1 is not null and v2 is     null then 2
             else 1 -- both v1 and v2 are null
           end as are_equal
    from test
    

    注意

    • 您不能混合使用这两种形式,并且
    • else 子句是可选的:如果未指定,则函数的返回值对于任何不匹配when 子句的值都是null,nad
    • 因为null 未通过所有测试(通过is [not] null 进行的显式无效测试除外),如果您需要检查null,您要么必须使用第二种形式(... case when x is null then y else z end),要么让空值通过并由else 子句处理。

    【讨论】:

    • 这是对这两种形式的一个很好的解释。我倾向于使用布尔形式,因为它更灵活。
    【解决方案2】:

    您的案例陈述总是可以更加明确。这是一个例子......

        select 
          case when v1 = v2 then 1
           when v1 <> v2 then 2
          end
        from test
    

    【讨论】:

    • @Trexion,请随时将答案更改为 Nicholas Carey 在下面的出色而详细的解释。我不会介意的。
    【解决方案3】:

    您所拥有的似乎正在发挥作用。您也可以使用!=&lt;&gt;

    select case 
      when v1 != v2 then 2
      else 1
      end 
    from test
    
    select case 
      when v1 <> v2 then 2
      else 1
      end 
    from test
    

    SQLFiddles: http://sqlfiddle.com/#!15/f5cac/5 http://sqlfiddle.com/#!15/f5cac/7

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2012-12-16
      • 2018-07-23
      • 1970-01-01
      相关资源
      最近更新 更多