基于列中值的不同条件进行SQL过滤

时间:2012-03-16 11:39:45

标签: sql oracle

我有一个分类器列,其值可以是X或Y.我的选择查询必须按日期过滤,如果列有x或y则考虑。

date BETWEEN i.valid_fromX AND i.valid_toX 
date BETWEEN i.valid_fromY AND i.valid_toY 

基本上我需要在SQL中等效以下内容:

if classifier == X {
  check if date is between valid_fromX to valid_toX
}   else if classifier == Y {
  check if date is between valid_fromY to valid_toY
}

3 个答案:

答案 0 :(得分:5)

你可以用常规和/或逻辑来做到这一点。如果分类器等于X,则此示例搜索1月;如果分类器等于Y,则搜索2月:

where  classifier = 'X' and date between '2012-01-01' and '2012-02-01'
       or
       classifier = 'Y' and date between '2012-02-01' and '2012-03-01'

答案 1 :(得分:2)

WHERE  ( classifier = 'X' AND [date] BETWEEN valid_fromX AND valid_toX )
        OR ( classifier = 'Y' AND [date] BETWEEN valid_fromY AND valid_toY )

答案 2 :(得分:0)

一个小变种:

where date between 
           case classifier when 'X' then valid_fromX when 'Y' then valid_fromY end 
           and case classifier when 'X' then valid_toX when 'Y' then valid_toY end