【发布时间】:2020-01-02 11:35:25
【问题描述】:
我试图仅从本月和上个月提取数据,但当日期跨越一年时,我有点困惑。
例如,我的初始查询只是从 Month(getdate()) and Month(getdate())-1 提取数据,这在这一年中运行良好,但是,由于今天是 2020 年 1 月 2 日,我的查询没有返回 2019 年 12 月的任何内容(显然,Month(getdate())-1 等于零) .
我现在将 where 子句更改为...
where Month(InstrDate) in (MONTH(getDate()),Month(DATEADD(month, -1, getdate())))
and year(InstrDate) in (year(getDate()),year(DATEADD(YEAR, -1, getdate())))
...现在这个月可以正常工作,但我想知道当“本月”和“上个月”在同一年内时下个月会发生什么。
我认为where 子句可以,因为它将返回(例如)今年和去年的二月和一月(?)但我认为我的案例陈述将不起作用,因为它将包括这两年。 .
case
when month(Instrdate) = Month(getdate()) and year(Instrdate) = year(getdate()) then 'This Month'
when month(Instrdate) = Month(DATEADD(month, -1, getdate())) and year(Instrdate) = year(DATEADD(year, -1, getdate()))then 'Last Month'
end as 'Month',
当然,我的“上个月”行将始终返回去年的上个月....如何确保它始终返回当前月份的前一个月?
更新:数据库是 SQL 2008 - 因此 EOMONTH 不是一个选项。
【问题讨论】:
标签: sql sql-server tsql sql-server-2008