简体   繁体   中英

SQL select where column clause

I have a table as follows

date1   |  date2  | datechoice

1-5-17    2-6-17      date2

Datechoice can either be date1 or date2. And I want to first look at the datechoice column to decide which column to use in the where statement.

Example Pseudo Code:

CASE WHEN datechoice ='date2' 
     THEN where date2 >= 2-2-17 AND where date2 <= 2-9-17 
     ELSE where date1 >= 2-2-17 AND where date1 <= 2-9-17

How can I do this?

WHERE (datechoice ='date1' and date1 >= '2017-02-02' AND date1 <= '2017-02-09')
   OR (datechoice ='date2' and date2 >= '2017-02-02' AND date2 <= '2017-02-09') 

This may be suspect for index use. I can't see how an index could be used since we have both dates conditinally being considered. An OR approach or two queries and a union may actually be more efficient.

WHERE case when datechoice = 'date1' then date1 
            when datechoice = 'date2' then date2 end 
            between '2017-02-02' and '2017-02-09'

Careful with between use I'm assuming date1 and date2 are actually date fields with no time component if time exists then you may have records missing on the upper boundary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM