简体   繁体   English

postgres中case表达式中的多个条件

[英]Multiple conditions in case expression in postgres

I am trying to order rows by string column like this:我正在尝试按字符串列对行进行排序,如下所示:

select * from cards
order by (case gate 
          when 'mastercard' then 1
          when 'visa' then 2
          when 'fibi' then 3
          when 'uzcard' then 4
          when 'humo' then 5 
          end)

But I want mastercard and visa have the same index.但我希望mastercardvisa具有相同的索引。 I tried something like this:我试过这样的事情:

select * from cards
order by (case gate 
          when 'mastercard' or 'visa' then 1
          when 'fibi' then 2
          when 'uzcard' then 3
          when 'humo' then 4
          end)

but I get this error:但我收到此错误:

ERROR: invalid input syntax for type boolean

Either create a second case with the same result, or convert your case to a full conditional.要么创建具有相同结果的第二个案例,要么将您的案例转换为完整的条件。

CASE has two forms: the base form is CASE有两个forms:基本形式是

CASE 
    WHEN condition THEN result
    WHEN condition THEN result
    ...
END

in which case condition is an arbitrary boolean expression, similar to a sequence of if/else if/else if in C, or the shortcut在这种情况下, condition是任意 boolean 表达式,类似于 C 中的 if/else if/else if 的序列,或快捷方式

CASE expression
    WHEN value THEN result
    WHEN value THEN result
    ...
END

in which case value is... just a simple value, similar to a switch statement in C.在这种情况下, value是......只是一个简单的值,类似于 C 中的switch语句。

Here you have the second form.这里有第二种形式。 'mastercard' or 'visa' is just plain nonsense, it's not SQL at all as it will attempt to treat 'mastercard' and visa' as booleans (which will fail, because neither is a valid boolean literal), then OR them, then will check if gate is equal to the result. 'mastercard' or 'visa'完全是胡说八道,根本不是 SQL 因为它会尝试将'mastercard'visa'视为布尔值(这将失败,因为两者都不是有效的 boolean 文字),然后OR他们,然后将检查gate是否等于结果。

You can either add a new case with the same result您可以添加一个具有相同结果的新案例

case gate 
          when 'mastercard' then 1
          when 'visa' then 1
          when 'fibi' then 2
          when 'uzcard' then 3
          when 'humo' then 4
          end

or expand the statement to a full conditional:或将语句扩展为完整的条件:

case
    when gate = 'mastercard' or gate = 'visa' then 1
    when gate = 'fibi' then 2
    ...

you can also use or operator here, this way you can prevent multiple when with same values and the list can be extended as well:您也可以在此处使用 or 运算符,这样您可以防止多个 when 具有相同的值,并且列表也可以扩展:

Case when gate in ('master_card','visa') then 1
     when gate = 'fibi' then 2
     .....
End as [column name as you want it to be]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM