MySQL difference between two rows of a SELECT Statement

后端 未结 5 1039
执笔经年
执笔经年 2020-11-27 20:53

I am trying to make the difference of two rows in an mysql database.
I have this table containing ID, kilometers, date, car_id, car_driver etc...
Since I don\'t alwa

5条回答
  •  攒了一身酷
    2020-11-27 21:35

    With MySQL 8 you can use CTE and ROW_NUMBER window function to make a more readable query

    WITH cte_name AS (
        SELECT
        ROW_NUMBER() OVER (ORDER BY update_time) as row_num,
        id,
        other_data,
        update_time
        FROM table_name WHERE condition = 'some_condition'
    )
    SELECT t2.id, t2.other_data, TIMEDIFF(t2.update_time, t1.update_time) AS time_taken
    FROM
    cte_name t1
    JOIN cte_name t2 ON t1.row_num = t2.row_num-1
    ORDER BY time_taken;
    

    In this example I'm trying get the difference between datetime values.

    • The idea is to use ROW_NUMBER window function to assign an incremental number to each row after ordering by update_time.
    • The CTE allows us to write a subquery without having to repeat writing the same code.
    • We self join the CTE. The joining condition is basically - each nᵗʰ item of the second subquery joins with the n-1ᵗʰ item of the first subquery (this also means the first row will disappear from the result set. if you need it you can use a UNION to add the first row to the start).

    There are some good tutorials for: CTE (Common Table Expression), ROW_NUMBER and even window functions

提交回复
热议问题