• Sorry I used the wrong date in the APPLY. It should have been this:

    SELECT

    DATEPART(wk, t.date) AS [Week],

    t.*,

    x.Sales52

    FROM #Test t

    OUTER APPLY

    (

    SELECT SUM(sales) AS Sales52

    FROM #Test

    WHERE

    ([Date] BETWEEN DATEADD (wk, -52, t.date)AND t.date)

    AND

    (market = t.market AND item = t.item)

    ) x

    Those numbers look good. It will only give you the total of the last 52 weeks. Notice how From 2014-12-21 to 2014-12-28 your total when down from 182 to 169 because the Sales from 2013-12-15 dropped. Of course you have to take into account the new current sales of 54 which was 13 less than 67.

    EDIT: Mind you there is room for tweaking the date range. I noticed for example that week 4 (2015-01-18) rolling total is including the week 4 sales from the previous year (2014-01-19). Which technically is accurate since that date is within the last 52 weeks. However it can easily be changed, at least the method is sound. Also this way you don't get NULLs when there isn't a full 52 weeks of data unless of course that is also intentional.


    SELECT quote FROM brain WHERE original = 1
    0 rows returned