Search code examples
sql-serverdatedate-rangems-query

How do I find Last year same MTD date range in SQL Server?


I am trying to find a MTD data from same month in last year. Can anyone help me to find that date range?

If I am pulling a data today, then today MTD will be 4/1/2017 - 4/10/2017 but I am looking for same date range as of last year 4/1/2016 - 4/10/2016

Here are the SQL query I came up with MTD this year,

LEFT JOIN 
   (SELECT 
        c2.ID AS CategoryID, 
        SUM(te.Price * te.Quantity) AS Sales,
        SUM(te.Cost * te.Quantity) AS Costs
    FROM   
        TransactionEntry te
    LEFT JOIN 
        Store s ON te.StoreID = s.ID
    INNER JOIN 
        [Transaction] t ON te.TransactionNumber = t.TransactionNumber 
                        AND te.StoreID = t.StoreID 
    LEFT JOIN 
        Item i ON te.ItemID = i.ID 
    LEFT JOIN 
        Category c2 ON i.CategoryID = c2.ID 
    WHERE  
        te.StoreID NOT IN (0, 2, 4, 17, 26) 
        AND t.Time >= DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) 
        AND t.Time < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
    GROUP BY 
        c2.ID) AS mtd

Solution

  • Unless you need something more parameterized, you can dateadd -1 years:

    select DATEADD(year, -1, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)), 
    DATEADD(year, -1, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1))
    

    Outputs 2016-04-01 & 2016-04-11

    In the context of your query:

    WHERE te.StoreID NOT IN (0, 2, 4, 17, 26) 
    AND t.Time >= DATEADD(year, -1, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)) 
    AND t.Time < DATEADD(year, -1, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1))