sql - Subtract values from line above the current line in MySQL -
i've following table:
| id | name | date of birth | date of death | result | | 1 | john | 3546565 | 3548987 | | | 2 | mary | 5233654 | 5265458 | | | 3 | lewis| 6546876 | 6548752 | | | 4 | mark | 6546546 | 6767767 | | | 5 | steve| 6546877 | 6548798 | |
and need whole table:
result = 1, if( current_row(date of birth) - row_above_current_row(date of death))>x else 0
to make things easier, guess, created same table above 2 id fields: id_minus_one , id_plus_one
like this:
| id | id_minus_one | id_plus_one |name | date_of_birth | date_of_death | result | | 1 | 0 | 2 |john | 3546565 | 3548987 | | | 2 | 1 | 3 |mary | 5233654 | 5265458 | | | 3 | 2 | 4 |lewis| 6546876 | 6548752 | | | 4 | 3 | 5 |mark | 6546546 | 6767767 | | | 5 | 4 | 6 |steve| 6546877 | 6548798 | |
so approach (in pseudo code):
for id=1, ignore result. (because there no row above)
for id=2, result = 1 if( (where id=2).date_of_birth - (where id_minus_one=id-1).date_of_death )>x else 0
for id=3, result = 1 if( (where id=3).date_of_birth - (where id_minus_one=id-1).date_of_death)>x else 0
and on whole table...
just ignore id_plus_one if there no need it, i'll use later same thing. so, if manage id_minus_one i'll manage id_plus_one same algorithm.
my question how pass pseudo code sql code, can't find way relate both ids in 1 select.
thank you!
as describe this, self join logic on select:
select t.*, ((t.date_of_birth - tprev.date_of_death) > x) flag t left outer join t tprev on t.id_minus_one = tprev.id
Comments
Post a Comment