SQL 中使用 CASE 语句时不等于

Tre*_*eha 6 sql postgresql case

在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
Run Code Online (Sandbox Code Playgroud)

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

有谁知道如何在caseSQL 语句中使用不等于吗?

小智 6

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

    select 
      case when v1 = v2 then 1
       when v1 <> v2 then 2
      end
    from test
Run Code Online (Sandbox Code Playgroud)