窗口函数+自连接解决?

我想显示每个阶段多少天。我们有很多项目,为简单起见,现在只显示一个ID。
对于第一阶段,应该是action_date创建的时间。
对于最后一个阶段,应该是今天-最后一个action_date(这些未完成的任务,这就是为什么我们从今天开始算起)
对于其他所有方面,这只是action_dates中的区别。
您如何使用SQL从上到下?提前非常感谢!

窗口函数+自连接解决?

wangyin2003 回答:窗口函数+自连接解决?

一种使用~ 680 [ms]lead()的方式:

union all

或更干净的解决方案(在我看来)取消数据透视:

select id,old_value,datediff(day,created,action_date) as days_in_stage
from t
where not exists (select 1
                  from t t2
                  where t2.id = t.id and t2.action_date < t.action_date
                 )
union all
select new_value,date_diff(day,action_date,lead(action_date,1,getdate()) over (partition by id order by action_date)
                ) as days_in_stage
from t;
本文链接:https://www.f2er.com/3164526.html

大家都在问