ollo ollo - 10 months ago 51
SQL Question

SQL filtering by different conditions based on values in column

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

Answer Source

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'
       classifier = 'Y' and date between '2012-02-01' and '2012-03-01'