我试图找到满足特定条件的两个时间戳之间的差异。我的表具有ID,时间戳,付款状态和子类型。对于某个ID,如果他们曾经进入付款状态“未付款”和子类型“ grace_period”,则我需要确定该ID是否曾经回到付款状态“已付款”和子类型“活动”。如果是这样,则最终结果必须是它们未付款的日期与活动的第一个日期之间的差额。我附了一张照片供参考。
我尝试使用IF / THEN语句和嵌套的case语句,但是它们都没有真正起作用。假设日期是真实的日期时间。
感谢您的帮助!
答案 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;