2015-03-02 73 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