Skip to content
Advertisement

Find first OPENED_DATE for every Denied or Accepted date in Postgresql

I need to find first document open date for request. For every request first step is opening a document and then it can be denied or accepted multiple times. I need to find first open_date between deny and accept dates. I tried LEAD function but it finds nearest one. My table looks like below:

My result should look like below:

I tried below query but it does not work like I want

Advertisement

Answer

This reads like a gaps-and-islands problem. Here is one approach:

The idea is to put records in groups (the islands), where each group ends with a non-opening action. How do we define the groups: with a count of non-opening actions that starts from the latest date in the table and goes backwards. Then, we can use window funtions to identify the start and end of each island, and exhibit the columns we are interested it with conditional aggregation.

Demo on DB Fiddle:

document_id | id | oper_name            | created_at          | open_date           | parent_id
----------: | -: | :------------------- | :------------------ | :------------------ | --------:
        102 | 28 | DOCUMENT_IS_DENY     | 2020-07-06 11:40:31 | 2020-07-06 11:40:18 |        24
        102 | 31 | DOCUMENT_IS_DENY     | 2020-07-06 11:48:30 | 2020-07-06 11:42:16 |        29
        102 | 36 | DOCUMENT_IS_ACCEPTED | 2020-07-06 15:48:30 | 2020-07-06 12:34:16 |        32
        102 | 38 | DOCUMENT_IS_DENY     | 2020-07-06 16:41:30 | 2020-07-06 16:20:45 |        37
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement