【问题标题】:Setting batch number for set of records in sql在sql中设置记录集的批号
【发布时间】:2024-01-20 18:41:01
【问题描述】:

我在 SQL 中有下表

id,date,records
1,2019-03-28 01:22:12,5
2,2019-03-29 01:23:23,5
3,2019-03-30 01:28:54,5
4,2019-03-28 01:12:21,2
5,2019-03-12 01:08:11,1
6,2019-03-28 01:01:21,12
7,2019-03-12 01:02:11,1

我想要实现的是设置一个批号,该批号在移动总和值超过 15 后应该继续增加,并且移动总和也应该重置,所以我正在尝试为总移动总和值为的记录创建批处理15

例如。如果移动总和变为 15,则批次数值应增加,这将给我包含总值为 15 的行。

所以我正在寻找的输出是

id,date,records, moving_sum,batch_number
1,2019-03-28 01:22:12,5,5,1
2,2019-03-29 01:23:23,5,10,1
3,2019-03-30 01:28:54,5,15,1
4,2019-03-28 01:12:21,2,2,2
5,2019-03-12 01:08:11,1,1,2
6,2019-03-28 01:01:21,2,12,2
7,2019-03-12 01:02:11,1,1,3

【问题讨论】:

  • 累计总和超过15会怎样?假设第一行是 7 而不是 5。
  • 那么第一行是批号 1,第二行是批号 2
  • 请用您正在使用的数据库标记您的问题@MysticRose: mysql, oracle, sql-server...?

标签: sql database recursive-query cumulative-sum


【解决方案1】:

你需要一个递归查询:

with 
    tab as (select t.*, row_number() over(order by id) rn from mytable t),
    cte as (
        select 
            id, 
            date, 
            records, 
            records moving_sum, 
            1 batch_number,
            rn
        from tab
        where rn = 1
        union all
        select
            t.id,
            t.date,
            t.records,
            case when c.moving_sum + t.records > 15 then t.records else c.moving_sum + t.records end,
            case when c.moving_sum + t.records > 15 then c.batch_number + 1 else c.batch_number end,
            t.rn
        from cte c
        inner join tab t on t.rn = c.rn + 1
    )
select id, date, records, moving_sum, batch_number from cte order by id

递归公用表表达式的语法因数据库而异,因此您可能需要稍作调整,具体取决于您的数据库。

还要注意,如果ids 以1 开头,并且始终无间隙地递增,则实际上您并没有公用表表达式tab,您可以在第二个中将rn 替换为id公用表表达式。

Demo on DB Fiddle

编号 |日期 |记录 |移动总和 |批号 -: | :--------- | ------: | ---------: | ------------: 1 | 2019-03-28 | 5 | 5 | 1 2 | 2019-03-29 | 5 | 10 | 1 3 | 2019-03-30 | 5 | 15 | 1 4 | 2019-03-28 | 2 | 2 | 2 5 | 2019-03-12 | 1 | 3 | 2 6 | 2019-03-28 | 12 | 15 | 2 7 | 2019-03-12 | 1 | 1 | 3

【讨论】:

  • 这太棒了.. 非常感谢。我正在尝试使用 Windows 功能,但这有效!
最近更新 更多