【问题标题】:Generate the SQL row numbers based on the 10 days filters根据 10 天过滤器生成 SQL 行号
【发布时间】:2020-09-03 08:41:04
【问题描述】:
 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,但这里的条件是......如果上面的Call_Date和下面的call_Date在10天之间,那么我们需要按顺序生成row_indicator,即(1,2,3, 4..) 如果没有,我们需要从 1 开始。

例如: 在上面的示例表中,前四行介于 10 天之间(小于或等于 240 小时),那么前四行的 row_indicators 为 1,2,3 ,4 再次从第五行开始,Call_Date 从 1 开始,因为第五行日期不在 10 天 Call_Date 范围内。

【问题讨论】:

  • 那么,您的问题是什么?你没有问任何问题,所以我们无法回答。 尝试了什么,为什么没有成功?
  • 到目前为止你尝试了什么?
  • 我已经尝试使用 LEAD() 和 Partition by Order by Clause ......但我只能将 row_numbers() 生成到表中。谢谢@GMB :) 您的代码适用于这种情况......很好的答案。再次感谢 GMB 的敏锐和有效。
  • 欢迎@venugopal。如果我的回答正确地回答了您的问题,那么点击复选标志accept it...谢谢!

标签: sql sql-server sql-server-2016 window-functions recursive-query


【解决方案1】:

为此,您需要一个递归查询。这个想法是通过升序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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多