Customer_Id Call_Date Agent_M_Code Row_Indicator
810471698 2020-03-19 13:25:24.910 rmanzan2 1
810471698 2020-03-22 20:28:19.067 pmaclair 2
810471698 2020-03-24 09:22:47.833 njeanle 3
810471698 2020-03-24 12:36:29.367 edelaro4 4
810471698 2020-03-29 22:36:29.762 kdularo7 1
810471698 2020-04-11 11:21:11.243 rbustam1 1
810471698 2020-04-11 17:50:41.023 frenteri 2
810471698 2020-05-10 11:16:21.683 cschuch2 1
810471698 2020-05-13 15:26:40.660 gledesma 2
810471698 2020-07-03 11:26:20.697 cmataver 1
810471698 2020-07-22 14:19:53.450 irodri13 1
对于上表,我需要生成row_indicator,但这里的条件是……如果上面的调用日期和下面的调用日期在10天之间,那么我们需要按顺序生成row_inindicator,即(1,2,3,4…(如果不是,我们需要从1开始。
例如:在上面的示例表中,前四行在10天之间(小于或等于240小时(,然后前四行的row_indicator为1、2、3、4,第五行的Call_Date从1开始,因为第五行日期不在10天Call_Date范围内。
您需要一个递归查询。其思想是通过递增call_date
来迭代地遍历表;第一个";每个日期的记录。只要一行比初始日期晚了10天以上,该值就会重置。
with
data as (select t.*, row_number() over(order by call_date) rn from mytable t),
cte as (
select d.*, call_date initial_date from data d where rn = 1
union all
select d.*,
case when d.call_date > dateadd(day, 10, c.initial_date)
then d.call_date
else c.initial_date
end
from cte c
inner join data d on d.rn = c.rn + 1
)
select customer_id, call_date, agent_m_code,
row_number() over(partition by initial_date order by call_date) row_indicator
from cte
order by call_date