Name | date | Hour | count |
---|---|---|---|
Mills | 2022-07-17 | twenty three | 12 |
Mills | 2022-07-18 | 00 | 15 |
Mills | 2022-07-18 | 01 | 20 |
Mills | 2022-07-18 | 02 | twenty two |
Mills | 2022-07-18 | 03 | 25 |
Mills | 2022-07-18 | 04 | 20 |
Mills | 2022-07-18 | 05 | twenty two |
Mills | 2022-07-18 | 06 | 25 |
Mike | 2022-07-18 | 00 | 15 |
Mike | 2022-07-18 | 01 | 20 |
Mike | 2022-07-18 | 02 | twenty two |
Mike | 2022-07-18 | 03 | 25 |
Mike | 2022-07-18 | 04 | 20 |
My current input table stores count information recorded continuously every hour of the day. I need to extract the difference of consecutive count values, but since I'm forced to use MySQL 5.7, I'm having trouble doing this.
The query I wrote is as follows:
SET @cnt := 0; SELECT Name, Date, Hours, Count, (@cnt := @cnt - Count) AS DiffCount FROM Hourly ORDER BY Date;
This does not give accurate results.
I would like to get the following output:
Name | date | Hour | count | difference |
---|---|---|---|---|
Mills | 2022-07-17 | twenty three | 12 | 0 |
Mills | 2022-07-18 | 00 | 15 | 3 |
Mills | 2022-07-18 | 01 | 20 | 5 |
Mills | 2022-07-18 | 02 | twenty two | 2 |
Mills | 2022-07-18 | 03 | 25 | 3 |
Mills | 2022-07-18 | 04 | 20 | 5 |
Mills | 2022-07-18 | 05 | twenty two | 2 |
Mills | 2022-07-18 | 06 | 25 | 3 |
Mike | 2022-07-18 | 00 | 15 | 0 |
Mike | 2022-07-18 | 01 | 20 | 5 |
Mike | 2022-07-18 | 02 | twenty two | 2 |
Mike | 2022-07-18 | 03 | 25 | 3 |
Mike | 2022-07-18 | 04 | 20 | 5 |
Mike | 2022-07-18 | 05 | twenty two | 2 |
Mike | 2022-07-18 | 06 | 25 | 3 |
Please suggest what I'm missing.
Try the following:
View the demo from db-fiddle.
In MySQL 5.7, you can update a variable inline to contain the updated "Count" value. Since you need to reset the variable when the value of "Name" changes, you can use another variable that contains the previous value of "Name". Then use the
IF
function to check:It will work with the
ABS
a> function, applying absolute values to the differences.See the demo here.
In MySQL 8.0 you can use something like
LAG
to get the output smoothly. It will be the same as:ABS
Apply the absolute difference value,COALESCE
is used to remove the first null value.See the demo here.