Listing out maximum price by titles with title name?

116 views Asked by At

I have a database for exercises. I would like to list out the maximum price of different types with the corresponding title name, but of course I can't just put the title name attribute into my SELECT clause, because it does not appear in the GROUP BY clause. Is there any solution to my problem? Thanks!

SELECT type, MAX(price) "price"
FROM titles
GROUP BY type
ORDER BY type DESC;
1

There are 1 answers

0
Gordon Linoff On BEST ANSWER

You don't mention the database you are using. Most databases support the ANSI standard row_number() and window/analytic functions. Here is one method to do what you want:

select type, name, price
from (select t.*, row_number() over (partition by type order by price desc) as seqnum
      from titles t
     ) t
where seqnum = 1;

In the case of MySQL, which does not support row_number(), you can do:

select type,
       substring_index(group_concat(name separator '|' order by price desc), '|', 1) as title,
       max(price) as price
from titles
group by type;

Note that this assumes that no title contains the character '|'.