简体   繁体   中英

How to get all rows with only the max year within each category of a table in MYSQL (version 5.7)

I have a table of multiple rows with the categories and years:

id category year
1 cat1 2022
2 cat1 2022
3 cat1 2021
4 cat2 2019
5 cat2 2019
6 cat2 2018
7 cat2 2018

I am trying to create a query that only gets the rows with the latest year for each category resulting in:

id category year
1 cat1 2022
2 cat1 2022
4 cat2 2019
5 cat2 2019

I have tried using GROUP BY but only get one row for each year and category:

SELECT 
 ANY_VALUE(`id`) AS `id`, 
 ANY_VALUE(`category`) AS `category`,
 MAX(`year`) AS `year` 
FROM `my_table` 
GROUP BY `category`,`year` 
ORDER BY `year` DESC, `category`

Any help would be much appreciated!

Reproduce next:

SELECT 
 ANY_VALUE(`my_table`.`id`) AS `id`, 
 ANY_VALUE(`my_table`.`category`) AS `category`,
 ANY_VALUE(`my_table`.`year`) AS `year` 
FROM `my_table`, (SELECT ANY_VALUE(`category`) AS `category`, MAX(`year`) AS `year` FROM `my_table` GROUP BY `category`) AS `my_table2` 
WHERE 
    `my_table`.`year` = `my_table2`.`year` AND
    `my_table`.`category` = `my_table2`.`category`  
ORDER BY `my_table`.`year` DESC, `my_table`.`category` 

Try below query with INNER JOIN :

SELECT DISTINCT(t1.id), t1.category, t1.year 
FROM my_table t1 
INNER JOIN my_table t2 
ON t1.category = t2.category
WHERE t1.year > t2.year;

This query is more efficient as it doesn't involve any subqueries, aggregate functions or grouping.

Check dbfiddle

This query is applicable for all relational databases because common keyword is used. The subquery portion retrieves category wise max year then join the main table and apply condition for picking desired result which contains same category comes multiple times in a year.

SELECT c.id, c.category, c.year 
FROM table_name c
INNER JOIN (SELECT category
         , MAX(year) "year"
        FROM table_name
        GROUP BY category) t_c
    ON c.category = t_c.category
       AND c.year = t_c.year;

here's a MySQL query for that:

SELECT * FROM TAB T1
WHERE YEAR >= ALL (SELECT YEAR FROM TAB T2 WHERE T2.CATEGORY = T1.CATEGORY);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM