首页 > 解决方案 > sql - 根据最大​​值检索某个组的元素,而不使用 GROUP BY

问题描述

我对 SQL 查询仍然很陌生,并且正在寻找一个(据说)相对简单的解决方案来解决我遇到的问题:

假设我有两个关系表:

+--------+------------+           +--------+--------+-------------+-------+
| TypeNr | TypeName   |           | BeerNr | TypeNr | BeerName    |  ABV  |
+--------+------------+           +--------+--------+-------------+-------+
|   1    |  Lager     |           |   1    |   1    | Budweiser   |  5    |
|   2    |  IPA       |           |   2    |   2    | Goose IPA   |  5.9  |
|   3    |  Trappiste |           |   3    |   2    | Goose So-Lo |  3    |
+--------+------------+           |   4    |   2    | Lost Palate |  6.3  |
                                  |   5    |   3    | Rochefort 8 |  8    |
                                  |   6    |   3    | Rochefort 10|  10   |
                                  +--------+--------+-------------+-------+

我想为每个相应的 TypeNr 返回具有最高 ABV 的行的 TypeName、BeerName 和 ABV。

通常我会查询这样的东西

SELECT table1.TypeName, MAX(table2.ABV)
FROM table1
INNER JOIN table2 ON table1.TypeNr = table2.TypeNr
GROUP BY table1.TypeName

哪个会返回:

Lager      5
IPA        6.3
Trappiste  10

我可以在这里使用什么替代方法,以便查询还返回与最高 ABV 关联的正确 BeerName?

Lager      Budweiser     5
IPA        Lost Palate   6.3
Trappiste  Rochefort 10  10

我觉得在尝试此操作时我不能再依赖 GROUP BY,因为我将被迫也按 BeerName 分组(因为我也在选择它)这不会产生我想要的结果。

标签: mysqlsqlgreatest-n-per-group

解决方案


推荐阅读