Question

I have been doing some research on this subject for a while, and thanks to a solution posted in another topic, I got close to solving this issue.

I am attempting to get the changes in a column of data: row(n) - row(n-1)

update Table tt1 
left outer JOIN Table tt2 
on tt1.name = tt2.name 
and tt1.date-tt2.date=1 
set tt1.delta = (tt1.amount-ifnull(tt2.amount, tt1.amount));

Output is

Date      |    Value   |    Delta
2013-03-30|    38651   |   393
2013-03-31|    39035   |   384
2013-04-01|    39459   |   0
2013-04-02|    39806   |   347

As you can see, the difference does not calculate for the first of April (the rest of the values are just fine). The same happens for the 1st day of every month.

My guess is that there is something to do with [and tt1.date-tt2.date=1], but I can't figure out exactly what.

Thanks for all your help in advance!

Was it helpful?

Solution

I made some changes to your statement... your error is either on the way you handle the dates or in the way you handle the delta...

update Table tt1 
left outer JOIN Table tt2 
on tt1.name = tt2.name 
and tt1.date = date_sub(tt2.date, interval 1 day)    
set tt1.delta = case when tt2.amount is not null then tt1.amount - tt2.amount else -1 end;

OTHER TIPS

try DATEDIFF this will give you the difference between two dates by days.

  and  DATEDIFF(tt1.date,tt2.date) =1 

this because you are differenting 01-31 and its not true thats why you get 0

so you should defference also the month.

One guess would be that the date is not stored as date but rather has a time component. You can get around this by converting to date using date() or using datediff():

update Table tt1 left outer JOIN
       Table tt2 
       on tt1.name = tt2.name and datediff(tt1.date, tt2.date) = 1 
    set tt1.delta = (tt1.amount-ifnull(tt2.amount, tt1.amount));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top