Home >Database >Mysql Tutorial >How do you calculate the difference in rows of a MySQL SELECT statement?
Calculating the Difference in Rows of a MySQL SELECT Statement
In MySQL, computing the difference between rows of a SELECT statement can be accomplished through various methods. One common approach is utilizing a self-join, enabling you to compare rows within the same table. Consider the following scenario:
Problem Statement:
You have a table containing data on vehicles, including their kilometers, date, car ID, and driver. However, due to varying data entry sequences, the data may be unsorted. You aim to create a view that displays the number of kilometers driven since the last entry for each car-driver combination, resulting in the following format:
ID | Kilometers | date | car_id | car_driver | number_km_since_last_date 1 | 100 | 2012-05-04 | 1 | 1 | 0 2 | 200 | 2012-05-08 | 1 | 1 | 100 4 | 600 | 2012-05-16 | 1 | 1 | 400 3 | 1000 | 2012-05-25 | 1 | 1 | 400
Solution 1: Join with Subquery
You can use a subquery within an INNER JOIN to retrieve the previous row's kilometers for each record:
SELECT mt1.ID, mt1.Kilometers, mt1.date, mt1.Kilometers - IFNULL(mt2.Kilometers, 0) AS number_km_since_last_date FROM myTable mt1 LEFT JOIN myTable mt2 ON mt2.Date = ( SELECT MAX(Date) FROM myTable mt3 WHERE mt3.Date < mt1.Date ) ORDER BY mt1.date
In this query, a subquery selects the maximum date before the current row's date, and this maximum date is then matched to a record in the LEFT JOIN.
Solution 2: Emulating Lag Function
MySQL does not offer a built-in lag() function, but you can imitate its behavior through a user-defined variable:
SET @kilo=0; SELECT mt1.ID, mt1.Kilometers - @kilo AS number_km_since_last_date, @kilo := mt1.Kilometers Kilometers, mt1.date FROM myTable mt1 ORDER BY mt1.date
In this query, the user-defined variable @kilo stores the previous row's kilometers. With each iteration, the user-defined variable is updated, effectively tracking the change in kilometers.
The above is the detailed content of How do you calculate the difference in rows of a MySQL SELECT statement?. For more information, please follow other related articles on the PHP Chinese website!