我如何找到一个事件时间戳与其后的第一个事件时间戳之间的差异,该差异与原始事件的时间戳不同?

时间:2019-08-01 16:56:30

标签: sql amazon-redshift

我试图找到满足特定条件的两个时间戳之间的差异。我的表具有ID,时间戳,付款状态和子类型。对于某个ID,如果他们曾经进入付款状态“未付款”和子类型“ grace_period”,则我需要确定该ID是否曾经回到付款状态“已付款”和子类型“活动”。如果是这样,则最终结果必须是它们未付款的日期与活动的第一个日期之间的差额。我附了一张照片供参考。

Need difference between those two dates

我尝试使用IF / THEN语句和嵌套的case语句,但是它们都没有真正起作用。假设日期是真实的日期时间。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

在以下情况下使用datediff和大小写

  select id,    
  datediff(day, max(case when paymentstate='paid' and subtype='active' then date end),
        max(case when paymentstate='unpaid' and subtype='grace_period' then date end)
        ) as ddiff from table group by id

答案 1 :(得分:0)

Redshift支持ignore null s选项,因此获取日期非常简单:

select t.*,
       datediff(day, date, next_pa_date) as diff_in_days
from (select t.*,
             lead(case when paymentstate = 'paid' and subtype = 'active' then date end ignore nulls) over (partition by id order by date) as next_pa_date
      from t
     ) t
where paymentstate = 'unpaid' and subtype = 'grace_period' and
      next_pa_date is not null;