SQL 如何在 db2 列选择查询中使用案例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25546567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 02:33:02  来源:igfitidea点击:

How to use case in db2 column select query

sqlselectdb2

提问by JulioBordeaux

I have a table in which there is a varchar column 'someid'and some timestamp columns: 'date_1', ... , date_4and 'xdate_1', ... , xdate_4I am trying to select two of them depending on 'someid' value, but had no luck until now. I am sure that this is syntax, googling also didn't help as all the examples were similar to my query.

我有一个表,其中有一个VARCHAR列'someid'和一些时间戳列: 'date_1', ... , date_4'xdate_1', ... , xdate_4我想选择其中两个依赖于“someid的价值,但没有运气,直到如今。我确信这是语法,谷歌搜索也没有帮助,因为所有示例都与我的查询相似。

Heres what I'm trying to do:

这是我想要做的:

select
  case
    when someid = 1 then date_1
    when someid = 2 then date_2
    when someid = 3 then date_3
    when someid = 4 then date_4
 ,case
    when someid = 1 then xdate_1
    when someid = 2 then xdate_2
    when someid = 3 then xdate_3
    when someid = 4 then xdate_4
from mytable;

回答by juergen d

You forgot the end

你忘记了 end

select
  case
    when someid = 1 then date_1
    when someid = 2 then date_2
    when someid = 3 then date_3
    when someid = 4 then date_4
  end as col1
 ,case
    when someid = 1 then xdate_1
    when someid = 2 then xdate_2
    when someid = 3 then xdate_3
    when someid = 4 then xdate_4
  end as col2
from mytable;

回答by Gordon Linoff

As a note, if someidis a character column, then you should use character comparisons:

请注意,如果someid是字符列,则应使用字符比较:

select (case when someid = '1' then date_1
             when someid = '2' then date_2
             when someid = '3' then date_3
             when someid = '4' then date_4
         end),
        . . .
from mytable;