I have a MySQL table like this :
x
+----+-----+-------+------+------+-------+---------------------+
| ID | GID | Name | p1 | p10 | p100 | createdAt |
+----+-----+-------+------+------+-------+---------------------+
| 1 | 100 | Item1 | 150 | 1499 | 10245 | 2020-07-04 12:00:00 |
| 2 | 857 | Item2 | 1047 | 9875 | 90000 | 2020-07-04 12:00:10 |
| 3 | 100 | Item1 | 149 | 1495 | 10245 | 2020-07-04 12:15:00 |
| 4 | 857 | Item2 | 1099 | 9875 | 89999 | 2020-07-04 12:15:10 |
| 5 | 100 | Item1 | 149 | 1495 | 10247 | 2020-07-04 12:30:00 |
| 6 | 857 | Item2 | 970 | 9879 | 89998 | 2020-07-04 12:30:10 |
+----+-----+-------+------+------+-------+---------------------+
What I try is to output for each unique GID
value their p1, p10, p100
of the two last most recent createdAt
Output example :
+-----+-------+------+------+-------+---------+----------+-----------+
| GID | Name | p1 | p10 | p100 | p1-last | p10-last | p100-last |
+-----+-------+------+------+-------+---------+----------+-----------+
| 100 | Item1 | 149 | 1495 | 10245 | 149 | 1495 | 10247 |
| 857 | Item2 | 1099 | 9875 | 89999 | 970 | 9879 | 89998 |
+-----+-------+------+------+-------+---------+----------+-----------+
I tried to use subqueries to achieve my goal but I am not confortable with that.
Thank you to anyone who can provide me informations and help.
Advertisement
Answer
You would use lag()
for this:
select gid, name, p1, p10, p100, prev_p1, prev_p10, prev_p100
from (select t.*,
lag(p1) over (partition by gid order by createdAt) as prev_p1,
lag(p10) over (partition by gid order by createdAt) as prev_p10,
lag(p100) over (partition by gid order by createdAt) as prev_p100,
row_number() over (partition by gid order by createdAt desc) as seqnum
from t
) t
where seqnum = 1;
Here is a db<>fiddle.
The subquery returns the previous values for each column. The outer query simply filters down to the most recent row for each gid
/name
combination.