This is the greatest-n-per-group problem that occurs frequently. My usual way to solve it is logically equivalent to @Martin Smith's answer, but does not use a subquery:
SELECT T1.Id, T1.name, T1.type, T1.price FROM Table T1 LEFT OUTER JOIN Table T2 ON (T1.type = T2.type AND T1.price < T2.price) WHERE T2.price IS NULL;
My solution and all the others provided in this thread have a chance to create several lines on the type value if more than one product has the same type and both have the same price, maximum. There are ways to resolve this and break the tie, but you need to tell us which product will โwinโ in this case.
You need another attribute that is guaranteed to be unique across all lines, at least for lines with the same type . For example, if a product with a high Id value needs to win, you can enable communication in this way:
SELECT T1.Id, T1.name, T1.type, T1.price FROM Table T1 LEFT OUTER JOIN Table T2 ON (T1.type = T2.type AND (T1.price < T2.price OR T1.price = T2.price AND T1.Id < T2.Id)) WHERE T2.price IS NULL;
Bill karwin
source share