How to get the last month data and month to date data

后端 未结 4 1273
小鲜肉
小鲜肉 2020-12-28 21:50

Need help in writing the query to get the last month data as well as month to date data.

If today\'s date is Mar 23 2011, I need to retrieve the data from last month

4条回答
  •  星月不相逢
    2020-12-28 22:40

    Step back one month, subtract the number of days to the current date, and add one day.

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

    To remove the time quickly, you can use this Cast( Floor( Cast( GETDATE() AS FLOAT ) ) AS DATETIME )

    So the second part would be (without time)

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

提交回复
热议问题