【问题标题】:Adding a new column with sequential numbers that repeat over and over again添加一个新列,其中的序号一遍又一遍地重复
【发布时间】:2022-01-16 01:49:19
【问题描述】:

我们如何在下面的查询结果中添加一列以便分配...

Key_Week1 to the 1st record 
Key_Week2 to the 2nd record 
Key_Week3 to the 3rd record 
   
Key_Week1 to the 4th record 
Key_Week2 to the 5th record 
Key_Week3 to the 6th record
   
Key_Week1 to the 7th record 
Key_Week2 to the 8th record 
Key_Week3 to the 9th record

And on and on and on...following the above pattern repeatedly?

Alternatively, you can use 1, 2 and 3 instead of Key_Week1, 
Key_Week2 and Key_Week3 for the new columns values
select distinct trunc(GenerateTimeBy1Day,'day') as claim_eff_date, trunc(GenerateTimeBy1Day,'day') + 20 AS bwe_to_complete_by from
(
    select from_dt + (level - 1)/1 as GenerateTimeBy1Day 
    from (select from_dt
        ,to_dt
        ,to_dt - from_dt + 1 as days_between    
    from (select to_date('22-Dec-2019') as from_dt
               , to_date('30-Dec-2040') as to_dt 
          from dual))
    connect by (level - 1) <= days_between  
)
order by claim_eff_date

当前结果: (只需运行上述查询即可。不需要样本数据)

Claim_Eff_Date BWE_To_Complete_By
22-DEC-19 11-JAN-20
29-DEC-19 18-JAN-20
05-JAN-20 25-JAN-20
12-JAN-20 01-FEB-20
19-JAN-20 08-FEB-20
26-JAN-20 15-FEB-20
02-FEB-20 22-FEB-20
09-FEB-20 29-FEB-20
16-FEB-20 07-MAR-20

期望的结果:

Claim_Eff_Date BWE_To_Complete_By Key_Week_Group
22-DEC-19 11-JAN-20 Key_Week1
29-DEC-19 18-JAN-20 Key_Week2
05-JAN-20 25-JAN-20 Key_Week3
12-JAN-20 01-FEB-20 Key_Week1
19-JAN-20 08-FEB-20 Key_Week2
26-JAN-20 15-FEB-20 Key_Week3
02-FEB-20 22-FEB-20 Key_Week1
09-FEB-20 29-FEB-20 Key_Week2
16-FEB-20 07-MAR-20 Key_Week3

Claim_Eff_Date BWE_To_Complete_By Key_Week_Group
22-DEC-19 11-JAN-20 1
29-DEC-19 18-JAN-20 2
05-JAN-20 25-JAN-20 3
12-JAN-20 01-FEB-20 1
19-JAN-20 08-FEB-20 2
26-JAN-20 15-FEB-20 3
02-FEB-20 22-FEB-20 1
09-FEB-20 29-FEB-20 2
16-FEB-20 07-MAR-20 3

不断地不断地

【问题讨论】:

    标签: oracle repeat row-number partition-by


    【解决方案1】:

    一种选择是计算row_number(),然后执行mod 得到repitition。

    with your_data as (
    select distinct trunc(GenerateTimeBy1Day,'day') as claim_eff_date, 
                    trunc(GenerateTimeBy1Day,'day') + 20 AS bwe_to_complete_by 
    from
    (
        select from_dt + (level - 1)/1 as GenerateTimeBy1Day 
        from (select from_dt
            ,to_dt
            ,to_dt - from_dt + 1 as days_between    
        from (select to_date('22-Dec-2019') as from_dt
                   , to_date('30-Dec-2040') as to_dt 
              from dual))
        connect by (level - 1) <= days_between  
    )
    order by claim_eff_date
    )
    select your_data.*,
           mod( row_number() over (order by claim_eff_date) - 1, 3 ) + 1 key_week_group
      from your_data
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      相关资源
      最近更新 更多