Skip to content
Advertisement

PSQL: How to compare record to previous record (2 tables)?

I have two tables:

01_System_Log

Records

I need to create a view, where the records of the last request id (3) are compared with the previous (2). So far I made a view, where the most actual records are shown.

I am not sure how to proceed, while in all compare examples, which I have found, only one table was used.

My ideal result is:

Advertisement

Answer

The information is all coming from one table "Records" so you just need to include that table twice in your query, using appropriate aliases, once to get the records with the highest request_id and once for the request_id which is lower than the highest. Finally you need to find what the highest request_id is, which you can do with a CTE on the "01_System_Log" table.

The CTE is straightforward:

The records that use the highest request_id are also easily found:

To get the records with the second highest request_id for each combination of firm and name you need to use a window function:

And then you tie it all together with sub-queries (and removing columns with duplicate information):

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement