简体   繁体   中英

MySQL - Subtracting value from previous row, group by 2 fields

I have the following dataset: 1 I want to subtract the 'flow' column values from previous row of same column of the same day. If there more entries at the same day subtract the first one from the last one of the same day This is the result I need: 2 There is an auto increment id

Do can do it like this:

SELECT
    t.myMax,
    t.`insertat`,
    IF(t.myMin = t.myMax, t1.myval, t2.`myval` - t1.`myval`) AS newval
FROM (
    SELECT insertat, min(id) AS myMin, max(id) AS myMax
    FROM myTable
    GROUP BY insertat) AS t
LEFT JOIN myTable  t1 ON t1.id = t.myMin
LEFT JOIN myTable  t2 ON t2.id = t.myMax;

sample

MariaDB [bernd]> SELECT * FROM myTable;
+----+------------+-------+
| id | insertat   | myval |
+----+------------+-------+
|  1 | 2021-01-01 |    44 |
|  2 | 2021-01-02 |    99 |
|  3 | 2021-01-02 |   134 |
|  4 | 2021-01-03 |    45 |
|  5 | 2021-01-04 |     2 |
|  6 | 2021-01-04 |    17 |
+----+------------+-------+
6 rows in set (0.01 sec)

MariaDB [bernd]> 
MariaDB [bernd]> SELECT
    -> t.myMax,
    -> t.`insertat`,
    -> IF(t.myMin = t.myMax, t1.myval, t2.`myval` - t1.`myval`) AS newval
    -> FROM (
    -> SELECT insertat, min(id) AS myMin, max(id) AS myMax
    -> FROM myTable
    -> GROUP BY insertat) AS t
    -> LEFT JOIN myTable  t1 ON t1.id = t.myMin
    -> LEFT JOIN myTable  t2 ON t2.id = t.myMax;
+-------+------------+--------+
| myMax | insertat   | newval |
+-------+------------+--------+
|     1 | 2021-01-01 |     44 |
|     3 | 2021-01-02 |     35 |
|     4 | 2021-01-03 |     45 |
|     6 | 2021-01-04 |     15 |
+-------+------------+--------+
4 rows in set (0.03 sec)

MariaDB [bernd]> 

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