棘手的 Postgresql 查询
Tricky Postgresql query
给出以下 table.
CREATE TABLE example (
a integer,
b integer,
c integer,
UNIQUE (a, b)
);
如何为每个 a
获取一行,使得 c
是 a
的最大值?
例如下面的 table,
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
诀窍是为您加入的派生 table 中的每个 a
找到最大值 c
,如下所示:
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
给出以下 table.
CREATE TABLE example (
a integer,
b integer,
c integer,
UNIQUE (a, b)
);
如何为每个 a
获取一行,使得 c
是 a
的最大值?
例如下面的 table,
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
诀窍是为您加入的派生 table 中的每个 a
找到最大值 c
,如下所示:
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