【问题标题】:How to get the last month data and month to date data如何获取上个月数据和本月至今数据
【发布时间】:2011-07-21 16:28:25
【问题描述】:

在编写查询以获取上个月数据以及当月至今的数据时需要帮助。

如果今天的日期是 2011 年 3 月 23 日,我需要检索上个月的数据和今天的数据(表示 2011 年 3 月 23 日)。

如果日期为 2011 年 4 月 3 日,则数据应包括 3 月月份数据和 2011 年 4 月 3 日之前的数据。

谢谢,

沙赫拉

【问题讨论】:

    标签: sql sql-server tsql sql-server-2008


    【解决方案1】:
    Today including time info  : getdate()
    Today without time info    : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 0)
    Tomorrow without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
    Beginning of current month : DATEADD(month, datediff(month, 0, getdate()), 0)
    Beginning of last month    : DATEADD(month, datediff(month, 0, getdate())-1, 0)
    

    很有可能

    WHERE dateColumn >= DATEADD(month, datediff(month, 0, getdate())-1, 0)
      AND dateColumn <  DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
    

    【讨论】:

    • 很好,我喜欢 datediff 解决方案。
    【解决方案2】:

    后退一个月,减去当前日期的天数,再加一天。

    WHERE  
      DateField <= GetDate() AND
      DateField >= DateAdd(
          mm, 
          -1, 
          DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
      )
    

    要快速删除时间,你可以使用这个 Cast( Floor( Cast( GETDATE() AS FLOAT ) ) AS DATETIME )

    所以第二部分是(没有时间)

    DateField >= Cast( Floor( Cast( (DateAdd(
              mm, 
              -1, 
              DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
          )) AS FLOAT ) ) AS DATETIME )
    

    【讨论】:

    • 不准确 - 第二个给出“2011-02-01 10:55:49.160”
    【解决方案3】:
    Select Column1, Column2 From Table1
    Where DateColumn <= GetDate() AND 
    DateColumn >= DATEADD(dd, - (DAY(DATEADD(mm, 1, GetDate())) - 1), DATEADD(mm, - 1, GetDate()))
    

    编辑:对 Russel Steen +1。在我知道他已经发布之前,我就发布了我的。

    【讨论】:

      【解决方案4】:

      Very helpful page

      declare @d datetime = '2011-04-03';
      
      declare @startDate datetime;
      select @startDate =
         CAST('01 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,-1,@d),113),8) AS datetime);
      select @startDate;
      

      【讨论】:

      • 感谢您提供链接。真的很有用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      相关资源
      最近更新 更多