我必须做一个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
感谢您的帮助。
答案 0 :(得分:3)
SELECT DISTINCT ON (a, b)
*
FROM person
ORDER BY a, b, modification_date DESC;
答案 1 :(得分:1)
SELECT
MAX
modification_date
个GROUP
A
(B
,JOIN
),然后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)
);