带有日期的where子句中的case语句

时间:2013-11-12 20:50:32

标签: sql date case

我正在努力避免硬编码付费日期。财政年度为10/1至9/30。

如果有人在7月1日到12月31日之间加入,那么付费截止日期是在下一个日历年,例如,2013年11月,某人已付款并获得2014年9月30日的付款。我需要2013年和2014年的付费

如果有人在1月1日到6月30日之间加入,那么付费截止日期是在当前日历年,例如今年1月将是​​2014年,并且他们的付款通过2014年9月30日,我不再需要2013年付费通过小组。

这就是我所拥有的: 如果getdate月份在1到6之间,那么我需要以当前年份的9/30 / +付费人员。如果getdate月份在7到12之间,那么我需要选择以当年9/30 +第二年的9/30付费。

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())

此查询只给我2013年9月30日,因为月份是11月(11)我需要2013年9月30日和09/30/2014付费日期。

由于

1 个答案:

答案 0 :(得分:1)

你需要围绕你的或条款。

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())
    )

由于你没有任何parens,即使另一部分没有通过,它仍然满足你的第一部分或第一部分的一部分。