SQL查询,每个独特二人组的最新行

时间:2014-03-14 08:36:43

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

我必须做一个SQL查询而且我不知道该怎么做。我想为每个独特的双人A / B获取最新的行。我正在使用postgresql。

例如:
表:人

id  A  B  modification_date
1   5  6  2014-04-12
2   6  7  2014-04-13
3   5  6  2014-04-14
4   9  1  2014-04-15
5   6  7  2014-04-16

我想得到:

id  A  B  modification_date
3   5  6  2014-04-14
4   9  1  2014-04-15
5   6  7  2014-04-16

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

SELECT DISTINCT ON (a, b)
       *
FROM   person
ORDER  BY a, b, modification_date DESC;

详细说明:
Select first row in each GROUP BY group?

答案 1 :(得分:1)

SELECT MAX modification_dateGROUP ABJOIN),然后id返回到原始行获取值(获取SELECT t1.* FROM Person t1 JOIN ( SELECT MAX(modification_date) max_date, A, B FROM Person GROUP BY A, B ) t2 ON t1.A = t2.A AND t1.B = t2.B AND t1.modification_date = t2.max_date 列所必需的):

id

更简单地说,如果您不关心哪些modification_date取回,并且即使MIN重复也只想要一行,您只需选择id imum值即可SELECT MIN(id) id, A, B, MAX(modification_date) modification_date FROM Person GROUP BY A, B 并完成它:

{{1}}

答案 2 :(得分:0)

SELECT id, a, b, modification_date
FROM person p
WHERE NOT EXISTS (
    SELECT *
    FROM person nx
    WHERE nxa = pa AND nx.b = p.b
    AND (nx.modification_date > p.modification_date
         OR nx.modification_date = p.modification_date AND nx.id > p.id)
    );