首页 > 解决方案 > 如何计算组的最大值?

问题描述

我有一张这样的表格(我不知道如何格式化表格)

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;

标签: mysqlsql

解决方案


where子句中使用过滤:

select t.*
from t
where t.purchases = (select max(t2.purchases) from t t2 where t2.category = t.category);

推荐阅读