SQL Group By and Order -- retrieve detail for most recent entries in table

Viewed 31

I want to Make a SQL Query that returns the newest Entry for each bot_id.

My current request looks like this, but it ALWAYS returns the first Entry. DESC & ASC don't make any difference:

SELECT bot_id, id
FROM t_request_history
GROUP BY bot_id
ORDER BY request_time DESC

The Tables looks like this:


t_request_history

id bot_id request response error request_time
1 usr_e74ae42b-080c-48e0-9e6c a a 0 2021-09-16 23:37:10
2 usr_e74ae42b-080c-48e0-9e6c a a 1 2021-09-16 23:37:35
3 usr_e74ae42b-080c-48e0-9e6c a a 1 2021-09-16 23:43:20
4 delete 1 1 1 2021-09-16 23:44:21
5 delete 1 1 0 2021-09-16 23:44:32
6 delete 1 1 0 2021-09-16 23:44:41



Wanted Result

bot_id id
delete 6
usr_e74ae42b-080c-48e0-9e6c 3

Actual Result

bot_id id
delete 4
usr_e74ae42b-080c-48e0-9e6c 1

Is there any way to make this query work?
2 Answers

It looks like your id values go up with time. That is, it looks like newer entries in your table have higher id values than older entries. If this is true,

SELECT bot_id, MAX(id) id
FROM t_request_history
GROUP BY bot_id

gets you what you want.

If the id values don't go up with time, you have to use a subquery to find the latest time for each bot_id.

                 SELECT bot_id, MAX(request_time) request_time
                   FROM t_request_history
                  GROUP BY bot_id

Then you join that subquery to your table like this:

SELECT a.bot_id, a.id
  FROM t_request_history a
  JOIN (
                    SELECT bot_id, MAX(request_time) request_time
                      FROM t_request_history
                     GROUP BY bot_id
       ) b   ON a.bot_id = b.bot_id
            AND a.request_time = b.request_time

The ON condition of the JOIN chooses just the rows with the latest times from your table.

Related