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.