SQL query for the longest time in each set of data

SQL query for the longest time in each set of data

Preface

Let’s first understand the business requirements. The blogger hasn't written about the backend for a long time, and this writing directly hit my knowledge blind spot. Let's
Insert image description here
briefly restore it. Here we use a table to simulate the
fields of the table.
Insert image description here
The contents of the table are as follows. Our requirement is to extract the data with the same name. The latest time.
Insert image description here
I don’t know what everyone will think of first. The first thing I thought of was to use group. At that time, I thought grouping was just group. It was so easy.
Insert image description here
Then I started trying it, and the result was. . . . .
Insert image description here
That doesn't seem to be the case. . . . Then I started my error resolution journey. . . .

Just when I wanted to give up, I suddenly came to my senses and began to think carefully about this requirement. Isn't it just to take out each name and the latest time, and then check it directly based on the name and the latest time? Isn't it the latest record? ?

So let’s see how to do it.

code

First, the first step is to find out the latest time corresponding to each name.

select name, max(dtime) from test group by name;

+------+---------------------+
| name | max(dtime)          |
+------+---------------------+
| xw   | 2023-05-22 20:01:43 |
| ll   | 2023-05-26 20:01:54 |
| oo   | 2023-05-03 20:01:56 |
+------+---------------------+

Then we only need to left join the data queried above and the data in the table.

select t2.* from (select t.name, max(t.dtime) dtime from test t group by name) t1 left join test t2 on t1.name=t2.name and t1.dtime=t2.dtime;

+----+------+---------------------+------+
| id | name | dtime               | info |
+----+------+---------------------+------+
|  2 | xw   | 2023-05-22 20:01:43 | 5-22 |
|  5 | ll   | 2023-05-26 20:01:54 | 5-26 |
|  6 | oo   | 2023-05-03 20:01:56 | 5-03 |
+----+------+---------------------+------+
3 rows in set (0.07 sec)

Then it's ok

Summarize

In fact, it's quite simple. I just lost my mind and didn't think about it, so I came to record it.

By the way, I would like to ask the experts if there is a more efficient method. If it is convenient, please share it in the comment area.

Insert image description here

Guess you like

Origin blog.csdn.net/qq_43627076/article/details/130814084