mysql - 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 分组(因为我也在选择它)这不会产生我想要的结果。
解决方案
推荐阅读
- python - 对象的描述符“__dict__”不适用于使用 type() 的对象
- javascript - 隐藏外部 URL,不知道它在电子上运行
- angularjs - SpringBoot:RestAPI 返回 JSON 数组但我希望在 AngularJS 中设置带有标签的值
- gitlab - 未经授权的错误:HTTP Basic:在 docker push registry.gitlab.com 上拒绝访问
- javascript - 如何在 Vuejs 上的 CKEditor 5 上激活和/或安装插件
- here-api - HERE Maps API 检索每个国家/地区的分层管理组
- google-sheets - 以近似匹配为条件的 GoogleSheet 值搜索
- java - 如何使用 Docx4J 向现有表中添加行
- amazon-web-services - 如何以编程方式获取 aws 短信发送报告?
- bash - 在 sed 中展开匹配的字符串