Home > Database > Mysql Tutorial > How to Retrieve the Latest Date for Each Group in MySQL?

How to Retrieve the Latest Date for Each Group in MySQL?

Mary-Kate Olsen
Release: 2025-01-24 08:26:08
Original
875 people have browsed it

How to Retrieve the Latest Date for Each Group in MySQL?

Get the latest date from MySQL grouped data

Retrieving the latest date associated with each group is useful when working with data grouped by specific categories. In the given scenario, you have a table containing data like this:

<code>| NO | model | date     | 
+---+-------+----------+
| 1  | bee   | 2011-12-01 |
| 2  | bee   | 2011-12-05 |
| 3  | bee   | 2011-12-12 |
| 4  | tar   | 2011-12-13 | </code>
Copy after login

To retrieve the latest date for each model group, use the following query:

<code class="language-sql">SELECT model, MAX(date) AS latest_date
FROM doc
GROUP BY model;</code>
Copy after login

This query will return the following result set:

<code>| model | latest_date | 
+-------+-------------+
| bee   | 2011-12-12  |
| tar   | 2011-12-13  | </code>
Copy after login
Copy after login

Alternatively, if you want to get all models with the largest date, you can use this query:

<code class="language-sql">SELECT model, date AS latest_date
FROM doc
WHERE date IN (SELECT MAX(date) FROM doc);</code>
Copy after login

This will return a result set like this:

<code>| model | latest_date | 
+-------+-------------+
| bee   | 2011-12-12  |
| tar   | 2011-12-13  | </code>
Copy after login
Copy after login

Note that the second method, in case there are multiple models with the same max date, will return all of them. The first method only returns the latest date for each group. Which method you choose depends on your specific needs.

The above is the detailed content of How to Retrieve the Latest Date for Each Group in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template