Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select specific changes using windowing functions in postgres

Tags:

sql

postgresql

I have a table with some foreign keys, I need to get a report of when these keys change.

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 table GROUP BY from,to;

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

I can do Group By to get the first two, transitions but it groups the third in with the first and I am not able to see it when it goes back.

I would like to make a query that gets following:

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

Is it possible?

like image 983
xordon Avatar asked May 10 '26 20:05

xordon


1 Answers

In PostgreSQL 8.4 you can use the window function LAG to access the previous row and compare it to see if it has the same values of "from" and "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

Result:

from  to    timestamp
1     2     0000        
1     3     0003        
1     2     0005    
like image 108
Mark Byers Avatar answered May 13 '26 15:05

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!