简体   繁体   English

寻找一种方法来将多行休假请求合并到基于请求的休假日期的一行中

[英]Looking for a way to consolidate multiple rows of time off requests to ranges in one row based off dates requested

I'm attempting to consolidate some Time off requests from multiple rows into one row which identifies the start and end time.我正在尝试将来自多行的一些休假请求合并到一行中,该行标识开始时间和结束时间。 The current table looks similar to the following;当前表格类似于以下内容;

ID ID hours per day每天几小时 Submitted Date提交日期 Requested Date申请日期 Requested Status请求状态
'Joe' “乔” 8 8 '2017-12-01' '2017-12-01' '2017-12-05' '2017-12-05' 'Approved' '得到正式认可的'
'Joe' “乔” 8 8 '2017-12-01' '2017-12-01' '2017-12-06' '2017-12-06' 'Approved' '得到正式认可的'
'Joe' “乔” 4 4 '2017-12-01' '2017-12-01' '2017-12-07' '2017-12-07' 'Declined' '拒绝'
'suzie' “苏西” 8 8 '2018-09-08' '2018-09-08' '2017-12-24' '2017-12-24' 'Approved' '得到正式认可的'
'suzie' “苏西” 8 8 '2018-09-08' '2018-09-08' '2017-12-25' '2017-12-25' 'Approved' '得到正式认可的'
'Joe' “乔” 2 2 '2017-12-01' '2017-12-01' '2017-12-7' '2017-12-7' 'Approved' '得到正式认可的'

I'm trying to condense this into the following:我试图将其浓缩为以下内容:

ID ID Total Hours全部小时数 Submitted Date提交日期 Requested Date Start要求的开始日期 Requested Date End要求的日期结束 Requested Status请求状态
Joe 16 16 '2017-12-01' '2017-12-01' '2017-12-05' '2017-12-05' '2017-12-06' '2017-12-06' Approved得到正式认可的
Joe 4 4 '2017-12-01' '2017-12-01' '2017-12-07' '2017-12-07' '2017-12-07' '2017-12-07' Declined拒绝
suzie苏西 16 16 '2018-09-08' '2018-09-08' '2017-12-24' '2017-12-24' '2017-12-25' '2017-12-25' Approved得到正式认可的
Joe 2 2 '2017-12-01' '2017-12-01' '2017-12-07' '2017-12-07' '2017-12-07' '2017-12-07' Approved得到正式认可的

I've tried dozens of things utilizing partitions but i'm not really getting anywhere.我已经尝试了许多使用分区的方法,但我并没有真正做到。 Any suggestions?有什么建议么?

This is a gaps and islands problem.这是一个空白和孤岛问题。 Assuming you are using MySQL 8+ we can use the difference in row numbers method here:假设您使用的是 MySQL 8+,我们可以在这里使用行号差异法:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY RequestedDate) rn1,
              ROW_NUMBER() OVER (PARTITION BY ID, RequestedStatus
                                 ORDER BY RequestedDate) rn2
    FROM yourTable
)

SELECT ID, SUM(hoursperday) AS total_hours, SubmittedDate,
       MIN(RequestedDate) AS rd_start, MAX(RequestedDate) AS rd_end,
       RequestedStatus
FROM cte
GROUP BY ID, SubmittedDate, RequestedStatus, rn1 - rn2
ORDER BY ID, RequestedStatus, MIN(RequestedDate);

下面演示链接的屏幕截图

Demo 演示

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

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