1

I have a classifier column that can have value of X or Y. My select query has to filter by date taking into account if the column has x or y.

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

Essentially I need the equivalent of the following in 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 Answers 3

5

You can do that with regular and/or logic. This example searches for January if classifier equals X, and for February if classifier equals Y:

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Why no brackets just in case?
2
WHERE  ( classifier = 'X' AND [date] BETWEEN valid_fromX AND valid_toX )
        OR ( classifier = 'Y' AND [date] BETWEEN valid_fromY AND valid_toY )

Comments

0

A minor variant:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.