繁体   English   中英

SQL-如何从上个月获取数据

[英]SQL - how to get data from previous month

我正在使用sql server2008。我想从上个月到查询运行的那一刻获取所有数据(在“ where”子句中)。 例如,如果今天是2014年4月1日,它将收集2014年1月1日至2014年1月31日之间的所有信息

这是一个简单的方法:

where year(datecol) * 12 + month(datecol) = year(getdate()) * 12 + month(datecol) - 1

此表达式不是“可保留的”,表示查询无法利用索引。 如果您有一个大表并且这很重要,则可以执行日期算术:

where datecol >= dateadd(month, -1, cast( (getdate() - datepart(day, getdate()) + 1) as date)) and
      datecol < cast( (getdate() - datepart(day, getdate()) + 1) as date)

解决问题的原因:

DATEPART(m,date_created)= DATEPART(m,DATEADD(m,-1,getdate()))和DATEPART(yyyy,date_created)= DATEPART(yyyy,DATEADD(m,-1,getdate()))

不要尝试使用本月的最后一天,像这样使用“下个月的第一天”既容易又可靠(请注意使用小于):

    select
    *
    from tables
    where (
            dateField >= "1st of this Month"
              and
            dateField < "1st of Next Month"
          (

计算:

    SELECT
          GETDATE()
          AS "getdate with time"

        , DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
          AS "getdate time truncated"

        , DATEADD(dd, -(DAY(GETDATE()) - 1), DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0))
          AS "day 1 this month"

        , DATEADD(MONTH, 1, DATEADD(dd, -(DAY(GETDATE()) - 1), DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)))
          AS "day 1 next month"
    ;

所以:

   select
    *
    from tables
    where (
            dateField >= DATEADD(dd, - (DAY(getdate()) - 1), DATEADD(dd, DATEDIFF(dd,0, getDate()), 0)) -- "1st of this Month"
              and
            dateField < DATEADD(month,1,DATEADD(dd, - (DAY(getdate()) - 1), DATEADD(dd, DATEDIFF(dd,0, getDate()), 0))) -- "1st of Next Month"
          (

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM