我正在HackerRank上try 解决这problem个问题.在这个问题中,我必须对连续的日期进行分组.当两个日期之间的差为1时,两个日期是连续的,并且在此问题陈述中,开始日期和结束日期始终是连续的.
我的方法是对连续的日期进行分组.为了识别连续日期,我使用了变量@rn
.当current start
日期等于之前的end date
时,我将得到相同的rn
,否则我将增加rn
.然后我想按rn
分组,并从每个组中获得min(start date)
和max(end date
)具有相同的rn
.但在实现这个逻辑之前,我遇到了一个问题,即即使when
条件是false
,@rn
变量也会增加.
set @rn = 0;
with tasks as (
select distinct Start_Date, End_Date
from Projects
order by Start_Date
)
select
Start_Date, End_Date,
case
when lag(End_Date, 1) over(Order by Start_Date) != Start_Date then @rn:=@rn+1
else @rn
end as cnt
from tasks
在上述查询中,即使当when
条件为false
时,也执行@rn := @rn+1
.
我遇到了这个问题,试图从HackeRank中解决a problem.
如果有人能解释为什么即使条件是false
也会执行@run := @rn+1
,那就太好了.
以下是上述查询为指定问题生成的输出:
我得到的输出:
2015-10-01 2015-10-02 0
2015-10-02 2015-10-03 1
2015-10-03 2015-10-04 2
2015-10-04 2015-10-05 3
2015-10-11 2015-10-12 24
2015-10-12 2015-10-13 5
2015-10-15 2015-10-16 24
2015-10-17 2015-10-18 24
2015-10-19 2015-10-20 24
2015-10-21 2015-10-22 24
2015-10-25 2015-10-26 24
...
我期待的输出
2015-10-01 2015-10-02 1
2015-10-02 2015-10-03 1
2015-10-03 2015-10-04 1
2015-10-04 2015-10-05 1
2015-10-11 2015-10-12 2
2015-10-12 2015-10-13 2
2015-10-15 2015-10-16 3
2015-10-17 2015-10-18 4
2015-10-19 2015-10-20 5
2015-10-21 2015-10-22 6
2015-10-25 2015-10-26 7
...