I have a table like so:
create table cars (
id serial primary key,
au_rating integer,
year integer
);
insert into cars (au_rating, year) VALUES
(1,2019),
(1,2020),
(1,2016),
(2,2016),
(2,2019),
(3,2020),
(3,2018),
(3,2017),
(3,2019),
(3,2020),
(0,2020),
(0,2006)
;
I want to select N first elements in each group using a JOIN LATERAL
(similar to this: https://stackoverflow.com/a/37862028/1002814):
SELECT cars_outer.id, cars_top.au_rating, cars_top.year
FROM cars cars_outer
JOIN LATERAL (
SELECT * FROM cars cars_inner
WHERE cars_inner.au_rating = cars_outer.au_rating
ORDER BY ABS(cars_inner.year - 2019)
LIMIT 2
) cars_top on true
ORDER BY cars_outer.au_rating DESC
However as I only want a max of 2 rows in each group of au_rating, I supplied a LIMIT 2
to the lateral join, however it seems to be ignored - why?