需要使用varchar和date数据类型为多个条件创建case语句

问题描述 投票:0回答:1

需要使用varchar和date数据类型为多个条件创建case语句,我的代码为sp:

select 
least(coalesce(case when 1.other_id=10 then 1.datestr else 0 end,
 case  when 2.info='Yes' then 2.date else 0 end))as date1,
from 
test1 as 1
left join test2 as 2 on 1.id = 2.id

我基本上想要获得两个条件之间的最低日期。两个条件都有一些过滤器(other_id = 10 in first,info =“Yes”in second)。对于那些条件,我想比较最短的日期。

sql case
1个回答
0
投票

我认为这是逻辑:

select (case when 1.other_id = 10 and 2.info = 'Yes'
             then least(case when 1.other_id=10 then 1.datestr end,
                        case when 2.info='Yes' then 2.date end
                       )
             when 1.other_id = 10 then 1.date
             else 2.date
        end)

或者,您可以在表达式中使用更合适的默认值。这样的事情(可能取决于数据库):

select least(case when 1.other_id = 10 then 1.datestr else '9999-01-01' end,
             case when 2.info = 'Yes' then 2.date else '9999-01-01' end)
            ) as date1,
© www.soinside.com 2019 - 2024. All rights reserved.