[英]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 ![]() |
hours per day![]() |
Submitted Date![]() |
Requested Date![]() |
Requested Status![]() |
---|---|---|---|---|
'Joe' ![]() |
8 ![]() |
'2017-12-01' ![]() |
'2017-12-05' ![]() |
'Approved' ![]() |
'Joe' ![]() |
8 ![]() |
'2017-12-01' ![]() |
'2017-12-06' ![]() |
'Approved' ![]() |
'Joe' ![]() |
4 ![]() |
'2017-12-01' ![]() |
'2017-12-07' ![]() |
'Declined' ![]() |
'suzie' ![]() |
8 ![]() |
'2018-09-08' ![]() |
'2017-12-24' ![]() |
'Approved' ![]() |
'suzie' ![]() |
8 ![]() |
'2018-09-08' ![]() |
'2017-12-25' ![]() |
'Approved' ![]() |
'Joe' ![]() |
2 ![]() |
'2017-12-01' ![]() |
'2017-12-7' ![]() |
'Approved' ![]() |
I'm trying to condense this into the following:我试图将其浓缩为以下内容:
ID ![]() |
Total Hours![]() |
Submitted Date![]() |
Requested Date Start![]() |
Requested Date End![]() |
Requested Status![]() |
---|---|---|---|---|---|
Joe![]() |
16 ![]() |
'2017-12-01' ![]() |
'2017-12-05' ![]() |
'2017-12-06' ![]() |
Approved![]() |
Joe![]() |
4 ![]() |
'2017-12-01' ![]() |
'2017-12-07' ![]() |
'2017-12-07' ![]() |
Declined![]() |
suzie![]() |
16 ![]() |
'2018-09-08' ![]() |
'2017-12-24' ![]() |
'2017-12-25' ![]() |
Approved![]() |
Joe![]() |
2 ![]() |
'2017-12-01' ![]() |
'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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.