如何使用postgres中的窗口函数选择特定的更改

xor*_*don 3 sql postgresql

我有一个带有一些外键的表,我需要得到这些键何时更改的报告.

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

可能吗?

Mar*_*ers 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
Run Code Online (Sandbox Code Playgroud)

结果:

from  to    timestamp
1     2     0000        
1     3     0003        
1     2     0005