为每个ID重复多次选择第二高的行

时间:2019-01-29 11:40:49

标签: postgresql

Id values
1 10
1 20
1 30
1 40
2 3
2 9
2 0
3 14
3 5 
3 7

答案应为

Id values
1 30
2 3
3 7

我尝试如下

Select distinct 
    id,
    (select max(values) 
     from table 
     where values not in(select ma(values) from table)
     )

1 个答案:

答案 0 :(得分:1)

您需要row_number window function。这将为每个组添加一个带有行数的列(在您的情况下为id)。在子查询中,您可以要求每组的第二行。

demo:db<>fiddle

{{1}}
相关问题