开发者社区> 问答> 正文

SQL获取日期范围仅从本月到上个月

我仅尝试从本月和上个月获取数据,但是当日期跨一年时,我会感到有些困惑。例如,我的初始查询只是提取Month(getdate()) and Month(getdate())-1当年运行良好的数据,但是由于今天是2020年1月2日,所以我的查询没有返回2019年12月的任何内容(显然Month(getdate())-1等于0)。

我现在将where子句更改为...


where Month(InstrDate) in  (MONTH(getDate()),Month(DATEADD(month, -1, getdate()))) 
and year(InstrDate) in  (year(getDate()),year(DATEADD(YEAR, -1, getdate()))) 

...现在这个月可以正常使用,但是我想知道当“本月”和“上个月”在同一年内时下个月会发生什么。

我认为该where条款是可以的,因为它将返回(例如)今年和去年的2月和1月(?),但是我认为我的案例声明将不起作用,因为它将包括这两个年份。

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不是一个选择。

展开
收起
Puppet 2020-01-03 22:37:17 577 0
1 条回答
写回答
取消 提交回答
  • 从上个月获取数据的最简单方法是:

    where datediff(month, Instrdate, getdate()) = 1 也就是说,日期和当前日期之间存在一个月的边界。

    这种方法的缺点是它不能在上使用索引Instrdate。也就是说,它不是可精炼的。

    另一种方法是:

    
    where instrdate < convert(date, dateadd(day, 1 - day(getdate()), getdate())) and
          instrdate >= dateadd(month, -1, convert(date, dateadd(day, 1 - day(getdate()), getdate())))
    
    2020-01-03 22:37:51
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
SQL Server在电子商务中的应用与实践 立即下载
GeoMesa on Spark SQL 立即下载
原生SQL on Hadoop引擎- Apache HAWQ 2.x最新技术解密malili 立即下载