按标题名称标题列出最高价格?

时间:2013-12-16 20:51:07

标签: sql group-by clause

我有一个练习数据库。我想列出具有相应标题名称的不同类型的最高价格,但当然我不能只将标题名称属性放入我的SELECT子句中,因为它不会出现在GROUP BY子句中。我的问题有什么解决方案吗?谢谢!

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

1 个答案:

答案 0 :(得分:1)

您没有提到您正在使用的数据库。大多数数据库都支持ANSI标准row_number()和窗口/分析函数。这是一种做你想做的事情的方法:

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;

对于不支持row_number()的MySQL,你可以这样做:

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

请注意,这假设没有标题包含字符'|'