我有一个带有一些外键的表,我需要获取这些键何时更改的报告。
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表GROUP BY from,to;
from | to | timestamp 1 | 2 | 0000 1 | 3 | 0003
我可以使用“分组依据”来获取前两个过渡,但是它将第三个与第一个过渡组合在一起,当它返回时我看不到它。
我想进行以下查询:
from | to | timestamp 1 | 2 | 0000 1 | 3 | 0003 1 | 2 | 0005
是否可以?
在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