2015-03-02 80 views
1

鉴于下表。Tricky Postgresql查询

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 
+3

也许这个问题的标题应该是“Not so t ricky SQL“ – Hogan 2015-03-02 19:13:27

+0

另请参见(可能重复?)http://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group?rq=1和(MySQL但一些便携式技术) http://stackoverflow.com/questions/8748986/get-records-with-highest-smallest-whatever-per-group – IMSoP 2015-03-05 12:46:36

回答

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 
+0

它应该是'example.a = max_c.a'在最后一行,而不是max_c.c – Srinath 2015-03-05 06:49:37

+0

@maandoo你说得对,很好。感谢您的注意。 – jpw 2015-03-05 12:38:11

+0

如果有多行具有相同“a”和“c”值的行,这将返回多行。 {1,0,2},{1,1,0},{1,2,2},{1,3,1},a = 1的内部查询中的“max_c”将是2,并且加入将匹配{1,0,2}和{1,2,2} – IMSoP 2015-03-05 12:43:53