mysql - 如何计算组的最大值?
问题描述
我有一张这样的表格(我不知道如何格式化表格)
Category / Products / Purchases
1 | A | 12
1 | B | 13
1 | C | 11
2 | A | 1
2 | B | 2
2 | C | 3
预期输出:
1 | B | 13
2 | C | 3
但是我不断得到
1 | A | 13
2 | A | 3
IE。它只选择第二列的第一次出现。这是我的代码:
SELECT Category, Products, MAX(Purchases) FROM myTable GROUP BY Category;
解决方案
在where
子句中使用过滤:
select t.*
from t
where t.purchases = (select max(t2.purchases) from t t2 where t2.category = t.category);
推荐阅读
- java - 没有事务的 JPA 更新查询 - 事务是强制性的吗?
- angular - 角度2在表中添加下一个兄弟
- python-2.7 - 使用 PyMC3 进行贝叶斯推理。编译错误。
- java - Java:从给定的全名字符串中删除逗号和姓氏
- ios - iOS 11 和 SSL SNI 支持
- mysql - 允许特定 mysql 用户的任何密码
- java - 为什么 b.wait() 不让主线程等待
- ruby-on-rails - 哈希斜线 (#/text) 用 /text 清除离开域的 url
- android - 添加 Google 地图支持时的 Gradle 问题
- maven - 带有依赖项的 Maven POM 打包