在 SQL 中使用 CASE 语句时不等于

Not equals when using CASE statement in SQL

在postgresql中,我有一个case语句,我需要添加一个"not equals"子句。

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 语句中使用不等于?

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

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

您所拥有的似乎正在工作。您也可以使用 !=<>.

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

首先,您从 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 子句的任何值的 return 值为 null,nad
  • 因为 null 除了通过 is [not] null 明确测试无效性之外的所有测试都失败了,如果你需要检查 null,你要么必须使用第二种形式(... case when x is null then y else z end) 或者让 null 落空并由 else 子句处理。