I have a table with the following data:
Fiscal Year | Fiscal Quarter | Fiscal Week | Data
2009 | 2 | 22 | 9.5
2009 | 2 | 24 | 8.8
2009 | 2 | 26 | 8.8
2009 | 3 | 28 | 8.8
2009 | 3 | 31 | 9.1
2009 | 3 | 33 | 8.8
I would like to write a query that would produce the following:
Fiscal Year | Fiscal Quarter | Fiscal Week | Data | Trend
2009 | 2 | 22 | 9.5 | NULL
2009 | 2 | 24 | 8.8 | -0.7
2009 | 2 | 26 | 8.8 | 0
2009 | 3 | 28 | 8.8 | 0
2009 | 3 | 31 | 9.1 | 0.3
2009 | 3 | 33 | 8.8 | -0.3
I know this can be easily achieved by doing a simple join of the table to itself with the previous fiscal week, however this will not always be a simple t1.[Fiscal Week] = t2.[Fiscal Week] - 2
because sometimes the difference is 3 weeks.
I can pull the max record easily with something like this:
SELECT
MAX(t1.[Fiscal Week]) "LastWeek"
FROM t1
WHERE t1.[Fiscal Year] = 2009
AND t1.[Fiscal Week] < 31
But I'm at a loss when it comes to abstracting it to make the join work.
How can I do a self join on "the largest fiscal week that is smaller than the current record"?