i need to write a query that will calculate difference between last month-end and month-end and difference between last year-end and month-end. I created sample database in sqlfiddle http://sqlfiddle.com/#!4/b9749 In my database the most important date is always the month-end but as you can see in the sample there there are other dates as well but i can't use values from these dates. When i run this query with condidtion that date ='2014-04-30' the result should be like this:
date product amount last_month_diff last_year_end_diff
2014-04-30 a1 350 -150 650
2014-04-30 b1 123 -123 1877
when i run this query with condidtion that date ='2014-05-31' the result should be like this
date product amount last_month_diff last_year_end_diff
2014-05-31 a1 400 -50 600
2014-05-31 b1 500 -377 1500
2014-05-31 c1 200 0 0
and when i run this query with condidtion that date ='2014-06-30' the result should be like this
date product amount last_month_diff last_year_end_diff
2014-06-30 b1 780 -280 1220
2014-06-30 c1 100 100 0
At first i thought i use analytical functions (lag) but i may have many dates between two month-ends and i don't know how to achieve the expected result.