简体   繁体   中英

How to get column difference between 2 rows in DB in SQL

I have a schema that looks like this

id, time, child_id

so its something like

1, 15, 2
2, 19, nil
3, 20, 5
4, 1, nil
5, 100, nil

I need to get the difference between the time of the parent and its child

so for the above data the result would be

id | time_difference
-------------------
1  |  4
3  |  80

so if a row has a child, it would take the child's time and subtract it from the parent. Assume that children don't have children of their own (a row is either a parent or a child)

As you only have a single level of parent/child, this can be done with a self join:

select p.id, 
       c.time  - p.time as time_difference
from the_table p
  join the_table c on c.id = p.child_id
where p.child_id is not null;

SQLFiddle: http://sqlfiddle.com/#!2/e882e/1

This approach let you choose the time unit of difference, say you want your time difference in seconds, minutes, hours.
mysql has an issue with time differences that hasn`t been fixed since long time ago.:

    Select
    a.id,   Time_To_Sec(b.time) - Time_To_Sec(a.time) As time_difference
    From   your_table a Left Outer Join
    your_table b On a.id = b.child_id 
    Group By 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM