| 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
IFfunction to check:It will work with the
ABSa> function, applying absolute values to the differences.SET @cnt := NULL; SET @name := NULL; SELECT Date, Hours, ABS(IF(@name = Name, @cnt := @cnt - Count, 0) ) AS DiffCount, (@name := Name) AS Name, (@cnt := Count) AS Count FROM tab ORDER BY Name DESC, Date, Hours;See the demo here.
In MySQL 8.0 you can use something like
LAGto get the output smoothly. It will be the same as:ABSApply the absolute difference value,COALESCEis used to remove the first null value.SELECT *, COALESCE(ABS( Count - LAG(Count) OVER( PARTITION BY Name ORDER BY Date, Hours ) ), 0) AS Diff FROM tab ORDER BY Name DESC, Date, HoursSee the demo here.