0

Lets suppose I have this table Purchases:

+----+------+-------+---------------------+
| ID | User | Price | Date                |
+----+------+-------+---------------------+
|  1 | Bob  |  35.0 | 2022-04-25 15:01:00 |
|  2 | Jeff |  12.0 | 2022-04-25 16:03:00 |
|  3 | Anna |  20.0 | 2022-04-25 17:09:00 | <- last from Anna
|  4 | Bob  |  10.0 | 2022-04-25 18:15:00 | <- last from Bob
|  5 | Susy |   5.0 | 2022-04-25 19:12:00 | <- last from Susy
|  6 | Jeff |  15.0 | 2022-04-25 20:25:00 | <- last from Jeff
+----+------+-------+---------------------+

The results I can get with this select:

select User, max(Price), min(Price), avg(Price) from Purchases group by User;

And I get this results:

+------+------------+------------+------------+
| User | max(Price) | min(Price) | avg(Price) |
+------+------------+------------+------------+
| Bob  |       35.0 |       10.0 |       22.5 |
| Jeff |       15.0 |       12.0 |       13.5 |
| Anna |       20.0 |       20.0 |       20.0 |
| Susy |        5.0 |        5.0 |        5.0 |
+------+------------+------------+------------+

This is my question: there is an aggregate function that brings the last value of each group?

+------+-------------+
| User | last(Price) |
+------+-------------+
| Bob  |        10.0 |
| Jeff |        15.0 |
| Anna |        20.0 |
| Susy |         5.0 |
+------+-------------+
Bill Karwin
  • 499,602
  • 82
  • 638
  • 795
  • 2
    There's no aggregate function, but there are other solutions. This type of query is asked about frequently on Stack Overflow. Usually they are tagged [tag:greatest-n-per-group]. – Bill Karwin Apr 25 '22 at 22:54

0 Answers0