Task: For each article, find the dealer or dealers with the most expensive price.
This problem can be solved with a subquery like this one:
SELECT article, dealer, priceFROM shop s1WHERE price=(SELECT MAX(s2.price) FROM shop s2 WHERE s1.article = s2.article)ORDER BY article;+---------+--------+-------+| article | dealer | price |+---------+--------+-------+| 0001 | B | 3.99 || 0002 | A | 10.99 || 0003 | C | 1.69 || 0004 | D | 19.95 |+---------+--------+-------+ The preceding example uses a correlated subquery, which can be inefficient (seeCorrelated Subqueries). Other possibilities for solving the problem are to use an uncorrelated subquery in theFROM clause, aLEFT JOIN, or a common table expression with a window function.
Uncorrelated subquery:
SELECT s1.article, dealer, s1.priceFROM shop s1JOIN ( SELECT article, MAX(price) AS price FROM shop GROUP BY article) AS s2 ON s1.article = s2.article AND s1.price = s2.priceORDER BY article;LEFT JOIN:
SELECT s1.article, s1.dealer, s1.priceFROM shop s1LEFT JOIN shop s2 ON s1.article = s2.article AND s1.price < s2.priceWHERE s2.article IS NULLORDER BY s1.article; TheLEFT JOIN works on the basis that whens1.price is at its maximum value, there is nos2.price with a greater value and thus the correspondings2.article value isNULL. SeeJOIN Clause.
Common table expression with window function:
WITH s1 AS ( SELECT article, dealer, price, RANK() OVER (PARTITION BY article ORDER BY price DESC ) AS `Rank` FROM shop)SELECT article, dealer, price FROM s1 WHERE `Rank` = 1ORDER BY article;