如何使用SQL MAX函数获取一行的所有字段?
考虑这个表(来自 http://www.tizag.com/mysqlTutorial/mysqlmax.php):
Id name type price
123451 Park's Great Hits Music 19.99
123452 Silly Puddy Toy 3.99
123453 Playstation Toy 89.95
123454 Men's T-Shirt Clothing 32.50
123455 Blouse Clothing 34.97
123456 Electronica 2002 Music 3.99
123457 Country Tunes Music 21.55
123458 Watermelon Food 8.73
此 SQL 查询返回每种类型中最昂贵的项目: SELECT type, MAX(price) FROM products GROUP BY type
Clothing $34.97
Food $8.73
Music $21.55
Toy $89.95
我还想获取每行属于上述最高价格的字段 id 和 name 。 什么样的 SQL 查询会返回这样的表?
Id name type price
123455 Blouse Clothing 34.97
123458 Watermelon Food 8.73
123457 Country Tunes Music 21.55
123453 Playstation Toy 89.95
Consider this table (from http://www.tizag.com/mysqlTutorial/mysqlmax.php):
Id name type price
123451 Park's Great Hits Music 19.99
123452 Silly Puddy Toy 3.99
123453 Playstation Toy 89.95
123454 Men's T-Shirt Clothing 32.50
123455 Blouse Clothing 34.97
123456 Electronica 2002 Music 3.99
123457 Country Tunes Music 21.55
123458 Watermelon Food 8.73
This SQL query returns the most expensive item from each type:
SELECT type, MAX(price) FROM products GROUP BY type
Clothing $34.97
Food $8.73
Music $21.55
Toy $89.95
I also want to get the fields id and name that belong to the above max price, for each row.
What SQL query will return a table like this?
Id name type price
123455 Blouse Clothing 34.97
123458 Watermelon Food 8.73
123457 Country Tunes Music 21.55
123453 Playstation Toy 89.95
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是经常出现的
greatest-n-per-group
问题。我通常的解决方法在逻辑上等同于@Martin Smith给出的答案,但不使用子查询:我的解决方案和迄今为止在该线程上给出的所有其他解决方案都有机会为
type 的每个值生成多行
,如果多个产品共享相同类型并且两者具有相同的价格,则为最高价格。有多种方法可以解决此问题并打破平局,但您需要告诉我们在这种情况下哪种产品“获胜”。您需要一些其他属性来保证在所有行中都是唯一的,至少对于具有相同
类型
的行来说是唯一的。例如,如果具有较大Id
值的产品应该获胜,您可以通过以下方式解决平局:This is the
greatest-n-per-group
problem that comes up frequently. My usual way of solving it is logically equivalent to the answer given by @Martin Smith, but does not use a subquery:My solution and all others given on this thread so far have a chance of producing multiple rows per value of
type
, if more than one product shares the same type and both have an equal price that is the max. There are ways to resolve this and break the tie, but you need to tell us which product "wins" in case like that.You need some other attribute that is guaranteed to be unique over all rows, at least for rows with the same
type
. For example, if the product with the greaterId
value should win, you can resolve the tie this way:编辑只是更新我的以满足明确的要求
Edit Just updating mine to meet the clarified requirement
完成
您可以使用子选择或内部联接来
You can do it with a subselect
or an inner join