在计算符合特定条件的列中的值之间的差异时需要帮助

Need help on calculating difference between values in the column that match certain condition

我有一个 table 包含以下列:

我需要为 articletype = "OUT" 和 action = "CREATE_ARTICLE" 的每一行计算其时间戳值与 articletype = "IN" 和 action = 的行的前一个时间戳值之间的差异"CREATE_ARTICLE" 都是关于同一个 ticket_id.

所以我需要知道从我收到消息 (articletype = "IN") 到我发送回复 (articletype = "OUT") 之间每张票经过了多少时间。动作 =“CREATE_ARTICLE”。应该计算两个连续时间戳之间的差异。

谢谢!

使用超前和滞后 select 下一行或前一行。这里有一些文档和示例。

https://www.postgresqltutorial.com/postgresql-lag-function/

max() 使用 window,对 articletype = 'IN' 使用过滤器:

select *, 
       case
         when articletype = 'OUT' 
           then timestamp 
             - max(timestamp) filter (where articletype = 'IN')
                 over (partition by ticketid
                           order by timestamp)
         else null
       end
  from table1
 where action = 'ARTICLE_CREATE'
   and articletype in ('IN', 'OUT');

window 的默认未指定记录范围是 rows between unbounded preceding and current row

Working fiddle 只有相关数据。