patternsqlMinor
multiple rows with the same maximum value
Viewed 0 times
rowssamethemaximumwithvaluemultiple
Problem
When I run the following query,
I am getting the correct engines and seats results but not the correct manufacturer, model combination. In addition, there are multiple rows with the same maximum value for seats number which I need but just getting one result by engines/seats. I have viewed other Stack Exchange posts and elsewhere but cannot seem to find a good solution to fix the query. Any advice?
SELECT engines, manufacturer, model, MAX(seats)
FROM planes
GROUP BY engines;I am getting the correct engines and seats results but not the correct manufacturer, model combination. In addition, there are multiple rows with the same maximum value for seats number which I need but just getting one result by engines/seats. I have viewed other Stack Exchange posts and elsewhere but cannot seem to find a good solution to fix the query. Any advice?
Solution
Yours appears to be a "greatest N per group" problem. What you can do is get the maximum seats per engine results:
and, using them as a derived table, join them back to the source to get the rows matching the maximums:
SELECT
engines,
MAX(seats) AS max_seats
FROM
planes
GROUP BY
enginesand, using them as a derived table, join them back to the source to get the rows matching the maximums:
SELECT
p.engines,
p.manufacturer,
p.model,
es.max_seats
FROM
planes AS p
INNER JOIN
(
SELECT
engines,
MAX(seats) AS max_seats
FROM
planes
GROUP BY
engines
) AS es
ON p.engines = es.engines
AND p.seats = es.max_seats
;Code Snippets
SELECT
engines,
MAX(seats) AS max_seats
FROM
planes
GROUP BY
enginesSELECT
p.engines,
p.manufacturer,
p.model,
es.max_seats
FROM
planes AS p
INNER JOIN
(
SELECT
engines,
MAX(seats) AS max_seats
FROM
planes
GROUP BY
engines
) AS es
ON p.engines = es.engines
AND p.seats = es.max_seats
;Context
StackExchange Database Administrators Q#148788, answer score: 7
Revisions (0)
No revisions yet.