简体   繁体   中英

Case statement in a where clause with dates

I am trying to avoid hardcoding paid thru dates. Fiscal year is 10/1 to 9/30.

If someone joins between July 1st and December 31st then the paid thru date is in the next calendar year, for example, it is November 2013, someone has paid and gets a paid thru of 09/30/2014. I need paid thru of 2013 and 2014

If someone joins between January 1st and June 30th then the paid thru date is in the current calendar year, for example this January it will be 2014, and they have a paid thru of 09/30/2014, I no longer need the 2013 paid thru group.

Here's what I have: If the getdate month is between 1 and 6 then I need to pull people with the paid thru of 9/30/ + the current year. If the getdate month is between 7 and 12 then I would need the selection to pull people with the paid thru of the 9/30 current year + 9/30 of following year.

select id, paid_thru, getdate()as today
from name
where datepart(mm,getdate())between 1 and 6 and datepart (yyyy,paid_thru)+1 = datepart(yyyy,getdate())
or 
datepart(mm,getdate()) between 7 and 12 and datepart (yyyy,paid_thru) = datepart(yyyy,getdate())

This query is only giving me the 09/30/2013, since the month is November (11) I need the 09/30/2013 and 09/30/2014 paid thru dates.

Thanks

You need parens around your or clauses.

select id,
    paid_thru,
    getdate() as today
from name
where
    (
        datepart( mm,getdate() ) between 1 and 6
        and datepart(yyyy,paid_thru) + 1 = datepart(yyyy,getdate())
    )
or
    (
        datepart(mm,getdate()) between 7 and 12
        and datepart (yyyy,paid_thru) = datepart(yyyy,getdate())
    )

Since you didn't have any parens, it was satisfying one part of your first or clause even though the other part didn't pass.

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