我有一张带有一些外键的表,我需要得到这些键何时更改的报告。
from | to | timestamp 1 | 2 | 0000 1 | 2 | 0001 1 | 2 | 0002 1 | 3 | 0003 1 | 3 | 0004 1 | 2 | 0005
SELECT from,to,FIRST(timestamp)FROM FROM GROUP BY from,to;
from | to | timestamp 1 | 2 | 0000 1 | 3 | 0003
我可以通过Group By来获得前两个转换,但它将第三个转换为第一个,并且当它返回时我无法看到它。
我想提出以下内容:
from | to | timestamp 1 | 2 | 0000 1 | 3 | 0003 1 | 2 | 0005
有可能吗?
答案 0 :(得分:5)
在PostgreSQL 8.4中,您可以使用窗口函数LAG访问上一行并进行比较,看它是否具有相同的“from”和“to”值:
SELECT "from", "to", timestamp
FROM
(
SELECT
"from",
"to",
timestamp,
LAG(("from", "to")) OVER (ORDER BY timestamp) AS prev
FROM Table1
) T1
WHERE ("from", "to") IS DISTINCT FROM prev
结果:
from to timestamp 1 2 0000 1 3 0003 1 2 0005