从最大值获取行ID

时间:2018-12-14 20:48:57

标签: sql postgresql

我是数据库新手

我有下表:

id  group       factor
------------------------
1   11          1
2   11          5
4   11          2
5   12          3
6   12          2
7   13          4
8   13          1
9   13          8
10  14          6

我需要获取基于其组的因素最大的ID,例如,对于第11组,具有最大因素的行是5,因此我需要获取该ID行,在这种情况下为2。

请有人告诉我正确的方法。

3 个答案:

答案 0 :(得分:2)

您可以使用:

SELECT DISTINCT ON(group) group factor, id
FROM tab
ORDER BY group, factor DESC;

db<>fiddle demo

答案 1 :(得分:0)

您可以为其使用简单的CTE(公用表表达式),如下所示:

with
x as (
  select group_id, max(factor) as max_factor from my_table group by group_id
)
select t.*
from my_table t
join x on x.group_id = t.group_id and x.max_factor = t.factor

此解决方案具有[期望?]功能,以防万一在同一组中的第一行有多行,它将显示全部,而不仅仅是其中的一个[随机]。

答案 2 :(得分:0)

如果您事先知道该群组,例如11,那么您可以简单地做到:

pick-a-descriptive-name-for-the-branch

否则,如果您想要表中存在的每个组的结果,那么Lukasz Szozda的答案就是前进的方式。