我有一个像这样的表(我不确定如何格式化表)
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
即它只是选择第二列的第一次出现。这是我的代码:
SELECT Category, Products, MAX(Purchases) FROM myTable GROUP BY Category;
SELECT PRODUCTS,MAX(PURCHASES) AS MAXP FROM TABLE GROUP BY PRODUCTS
在where
子句中使用过滤:
select t.*
from t
where t.purchases = (select max(t2.purchases) from t t2 where t2.category = t.category);
不存在:
select m.* from myTable m
where not exists (
select 1 from myTable
where category = m.category and purchases > m.purchases
)
请参见demo。结果:
| Category | Products | Purchases |
| -------- | -------- | --------- |
| 1 | B | 13 |
| 2 | C | 3 |