How can I get the last 12 months from the current date PLUS extra days till 1st of the last month retrieved

后端 未结 3 1878
名媛妹妹
名媛妹妹 2021-01-18 03:48

Getting the last 12 months from a specific date is easy and can be retrieved by the following command in SQL-server. Its answer is 2014-08-17.

select Dateadd         


        
3条回答
  •  梦谈多话
    2021-01-18 04:33

    Using DATEADD and DATEDIFF:

    DECLARE @ThisDate DATE = '20150817'
    SELECT DATEADD(YEAR, -1, DATEADD(MONTH, DATEDIFF(MONTH, '19000101', @ThisDate), '19000101'))
    

    For more common date routines, see this article by Lynn Pettis.


    To use in your WHERE clause:

    DECLARE @ThisDate DATE = '20150817'
    SELECT *
    FROM 
    WHERE
         >= DATEADD(YEAR, -1, DATEADD(MONTH, DATEDIFF(MONTH, '19000101', @ThisDate), '19000101'))
    

提交回复
热议问题