【问题标题】:Case statement in a where clause with dates带日期的 where 子句中的 case 语句
【发布时间】:2013-11-12 20:50:32
【问题描述】:

我试图避免硬编码截止日期。会计年度为 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())

这个查询只给我 09/30/2013,因为月份是 11 月 (11) 我需要 09/30/2013 和 09/30/2014 支付截止日期。

谢谢

【问题讨论】:

  • 您使用的是哪个 DBMS?
  • @user2984972 你解决了吗?

标签: sql date case


【解决方案1】:

你需要在 or 子句周围加上括号。

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

由于您没有任何括号,因此它满足了您的第一个 or 子句的一部分,即使另一部分没有通过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2021-11-30
    • 2020-03-26
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多