首页 > 解决方案 > 使用棘手的分组查询

问题描述

请帮帮我,我有这样的桌子:

id1, id2, quantity
1    1    5
2    1    3
3    1    0
2    3    10
1    3    4

我只需要获取 id1 和 id2 值,其中数量最大按 id2 分组。请帮我。

第一个 id - 它是好 (id2) 所在的 id。Q - q 每个仓库。完美的结果是这样的:

id1, id2, quantity
1    1    5
2    3    10

或类似的东西。我需要知道具有 MAX 数量的产品 ID (id2) 和存储 ID (id1) 以及此类产品的其他存储。也很容易得到结果 MAX(q)。

标签: sql

解决方案


这是你想要的吗?

select t.*
from t
order by quantity desc
fetch first 1 row only;

这将获取数量最多的行。或这个?

select t.*
from t
where t.quantity = (select max(t2.quantity) from t t2 where t2.id2 = t.id2);

推荐阅读