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

时间:2014-08-14 10:52:50

标签: sql sql-server-2008 date

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

3 个答案:

答案 0 :(得分:2)

这是一个简单的方法:

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

此表达式不是" sargable",表示查询无法利用索引。如果你有一个大表,这很重要,那么你可以做日期算术:

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

答案 1 :(得分:0)

是什么解决了它:

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

答案 2 :(得分:0)

不要尝试一个月的最后一天,使用&#34;下个月的第一天&#34;更容易,更可靠。像这样(注意使用少于):

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