我有一个这样的表格(我不确定如何格式化表格)
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;
答案 0 :(得分:1)
在where
子句中使用过滤:
select t.*
from t
where t.purchases = (select max(t2.purchases) from t t2 where t2.category = t.category);
答案 1 :(得分:1)
不存在:
equipmentID = bytes(equipmentID_hex, 'utf-8')
请参见demo。
结果:
select m.* from myTable m
where not exists (
select 1 from myTable
where category = m.category and purchases > m.purchases
)
答案 2 :(得分:0)
您可以使用row_number()来确定每个组的最大购买量,或者如果每个组有最大购买量,则将rownumber()替换为rank()
Select Category, Products,
Purchases from (Select Category,
Products,
Purchases,
row_number() over (partition by
category, products order by
purchases desc) rn from table) t
where t.rn=1
)