0

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

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

1 回答 1

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;

对于不支持的 MySQL,row_number()您可以执行以下操作:

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

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

于 2013-12-16T21:36:50.810 回答