postgres选择查询3列,最大值

时间:2016-01-28 08:04:51

标签: postgresql greatest-n-per-group

我有这个样本表:

id    branch    branch_running_no
1      1         5
2      1         10
3      2         5
4      2         10
5      3         5
6      3         10
7      4         5
8      4         10
9      5         5
10     5         10

使用此查询,我可以获取每个分支列的max branch_running_no,但我还想包含max branch_running_no的列id。

SELECT branch, MAX(branch_running_no) from table1 GROUP BY branch order by branch;

我能够实现:

branch    max
1         10
2         10
3         10
4         10
5         10

但我需要:

id    branch    max
2     1         10
4     2         10
6     3         10
8     4         10
10    5         10

2 个答案:

答案 0 :(得分:1)

SELECT id
     ,branch
     ,branch_running_no
FROM (
    SELECT id
           ,branch
           ,branch_running_no
           ,row_number() OVER (PARTITION BY branch ORDER BY branch_running_no DESC) rn
    FROM t
    ) t
WHERE rn = 1

SELECT distinct on(branch) id,branch, MAX(branch_running_no) from t GROUP BY id,branch order by branch,3 desc;

答案 1 :(得分:0)

SELECT id,branch,MAX(branch_running_no)来自table1 GROUP BY id,分支顺序by id,branch;