简体   繁体   中英

MySQL - Subtract 1st column of 1st row with 2nd column of 2nd row

I'm struggling with a Mysql Code, and I have no clue how to solve this. I have two columns with time value on which I've ordered by desc in Mysql Query result.

I need to find out the differences between the 2nd row StateEndTime and the 1st-row StateStarTtime nd so on and display this in a new row/column. The final table should look like this :

ID          Type         StateStarTtime    StateEndTime   Min Difference

xxx         YYY          03:57             03:59          00:02
xxx         ZZZ          03:53             03:55          00:04
xxx         ZZZ          03:46             03:49          
SELECT id,startTime,endTime,type,TIMEDIFF(endTime,startTime) as min_df FROM tasks where 1

You must get the max(stateendtime) that is less than the current row's stateendtime
and subtract it from statestarttime :

select 
  t.*,
  left(timediff(
   t.statestarttime, 
   select max(stateendtime) from tablename where stateendtime < t.stateendtime
  ), 5) mindifference
from tablename t
order by t.statestarttime desc

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