The method of taking the maximum value of SQL grouping

This blog post is written to help people who encounter the same problem, I hope it will be useful to you~

Question: How to find out the record with the longest time in the same course id? (As shown below)


1. At first, I wanted to group the course id by group by, and then get the maximum value, as follows:

SELECT MAX(l.learn_time)
FROM learn l
where l.user_id = '14201109'
GROUP BY l.course_id

The results are as follows:


But I want to find out all the fields, so add learn.* after the select, well, it should be no problem, as follows:

SELECT MAX(l.learn_time), l.*
FROM learn l
where l.user_id = '14201109'
GROUP BY l.course_id

But the results I found out were beyond my expectations. Did you not expect that the time fields of the two columns are not the same! ! !

Therefore, it is thought that the maximum time of MAX(l.learn_time) should not be directly related to the following learn.* records.


At the beginning, I thought like this, sorted by reverse time,

select learn.*
from learn
where	learn.user_id = '14201109'
ORDER BY learn.learn_time DESC

Then you should be able to get it by grouping by course id, but the order by must be placed after the group by, like the following

select learn.*
from learn
where	learn.user_id = '14201109'
GROUP BY course_id
ORDER BY learn.learn_time DESC

It turns out that learn_id is 1 and 6. After grouping by group by, it can only get these two records. These two records are exactly the smallest time, and what we want is the maximum time when learn_id is 5 and 9. After I really don't know how to solve this torture, so I sent a distress message. After a while, with the help of my classmates, I solved only one problem. In fact, the idea at the beginning was right, that is to find the maximum time first. It's good to nest the query outside, as follows:

correct answer:

SELECT *
from learn
where learn.learn_time in (
			SELECT MAX(l.learn_time)
			FROM learn l
			where l.user_id = '14201109'
			GROUP BY l.course_id
)

In fact, I thought about it at the beginning, but I wrote the equal sign "=" in in, and I kept getting an error saying that only one record can be found in the nesting. At that time, my brain was short-circuited, so I didn't think of using in [/ Cover your face][/cover your face][/cover your face], I hope you don't make the same mistakes as I did.

Suddenly remembered and forgot to say, I am using mysql database


Finally, if you think what I wrote is okay, give it a like and follow it. ^v^




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324737693&siteId=291194637