棘手的Postgresql查询

时间:2015-03-02 19:07:22

标签: sql postgresql greatest-n-per-group

鉴于下表。

CREATE TABLE example (
    a integer,
    b integer,
    c integer,
    UNIQUE (a, b)
);

如何为每个a获取一行,ca的最大值?

例如,如下表所示,

a|b|c
-----
1 1 1
1 2 2
2 1 9
3 2 4
3 3 5
3 4 6

我应该回来了

a|b|c
-----
1 2 2
2 1 9
3 4 6

1 个答案:

答案 0 :(得分:1)

诀窍是找到您加入的派生表中每个c的最大a,如下所示:

select a, b, c
from example
join (select a, max(c) max_c from example group by a) max_c
on example.a = max_c.a and example.c = max_c.max_c
相关问题