简体   繁体   English

在 AMDP/MYSQL 中根据连续日期汇总行的列值

[英]Summing up column values of rows based on consecutive date in AMDP/MYSQL

I am trying to convert one SAP ABAP code into newly introduced language SAP AMDP(ABAP Managed Database Procedures) which is based on MYSQL.我正在尝试将一个 SAP ABAP 代码转换为基于 MYSQL 的新引入的语言 SAP AMDP(ABAP 托管数据库过程)。

I want to sum up column values of of rows if they with consecutive dates meaning if Start date of Next row is Next day of End date of current row then the value should sum up.我想总结行的列值,如果它们具有连续的日期,这意味着如果下一行的开始日期是当前行的结束日期的第二天,那么该值应该相加。

For ex: Below is my source table例如:下面是我的源表

EMP Startdate   Enddate amount 
1   1/1/2020    1/3/2020    2
1   1/4/2020    1/7/2020    3
1   1/8/2020    1/10/2020   4

1   1/15/2020   1/18/2020   5

2   1/3/2020    1/6/2020    3

2   1/12/2020   1/15/2020   4
2   1/16/2020   1/20/2020   5

3   1/4/2020    1/8/2020    5
3   1/9/2020    1/11/2020   6

3   1/14/2020   1/18/2020   7

3   1/21/2020   1/24/2020   7
3   1/25/2020   1/27/2020   5

The Second row's start date(4-Jan) is next day of End date(3-jan) of first row and same for 3rd row.第二行的开始日期 (4-Jan) 是第一行结束日期 (3-jan) 的第二天,第三行也是如此。

So result should come as single row with start date of first row and end date of third row and total of all three rows.所以结果应该是单行,第一行的开始日期和第三行的结束日期以及所有三行的总和。 Expected result should be like below.预期结果应如下所示。

EMP Startdate   Enddate amount

1   1/1/2020    1/10/2020   9

1   1/15/2020   1/18/2020   5

2   1/3/2020    1/6/2020    3

2   1/12/2020   1/20/2020   9

3   1/4/2020    1/11/2020   11

3   1/14/2020   1/18/2020   7

3   1/21/2020   1/27/2020   12

This is a gaps and islands problem, where you want to group together "adjacent" rows.这是一个间隙和孤岛问题,您希望将“相邻”行组合在一起。 I have no knowledge in AMDP, but in MySQL you could approach this with window functions:我对 AMDP 一无所知,但在 MySQL 中,您可以使用窗口函数来解决这个问题:

select emp, min(start_date) start_date, max(end_date) end_date, sum(amount) amount      
from (
    select t.*, sum(case when start_date = lag_end_date + interval 1 day then 0 else 1 end) over(partition by emp order by start_date) grp
    from (
        select t.*, lag(end_date) over(partition by emp order by start_date) lag_end_date
        from mytable t
    ) t
) t
group by emp, grp 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM