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!
latest year for each category
why docat1
andcat2
appear twice? – user3783243ID
s are different – Aksen P