从每个组中选择一个最大行

时间:2011-09-19 10:08:16

标签: mysql correlated-subquery

在示例Xaprb中 http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/ 为每个组选择最大值

+--------+------------+-------+
| type   | variety    | price |
+--------+------------+-------+
| apple  | gala       |  2.79 | 
| apple  | fuji       |  0.24 | 
| apple  | limbertwig |  2.87 | 
| orange | valencia   |  3.59 | 
| orange | navel      |  9.36 | 
| pear   | bradford   |  6.05 | 
| pear   | bartlett   |  2.14 | 
| cherry | bing       |  2.55 | 
| cherry | chelan     |  6.33 | 
+--------+------------+-------+

select type, variety, price
from fruits
where price = (select min(price) from fruits as f where f.type = fruits.type);

+--------+----------+-------+
| type   | variety  | price |
+--------+----------+-------+
| apple  | fuji     |  0.24 | 
| orange | valencia |  3.59 | 
| pear   | bartlett |  2.14 | 
| cherry | bing     |  2.55 | 
+--------+----------+-------+

但如果我有一些价格水果,那么记录是重复的

+--------+----------+-------+
| type   | variety  | price |
+--------+----------+-------+
| apple  | fuji     |  0.24 | 
| apple  | fuji2    |  0.24 |
| orange | valencia |  3.59 | 
| pear   | bartlett |  2.14 | 
| cherry | bing     |  2.55 | 
+--------+----------+-------+

在这种情况下,我如何只获得每种类型一条记录?

2 个答案:

答案 0 :(得分:0)

只需按type

分组
select type, MIN(variety) AS variety, MIN(price) AS price
from fruits
where price = (select min(price) from fruits as f where f.type = fruits.type);
GROUP BY type

这是你得到第一个项目(按字母顺序排列)

BTW:您也可以使用MAX,只是您喜欢的

答案 1 :(得分:0)

使用GROUP BY子句 - 即

 select type, variety, price
 from fruits
 where price = (select min(price) from fruits as f where f.type = fruits.type)
 group by type;