gpt4 book ai didi

mysql - 使用 SQL 查找先前的、不连续的日期

转载 作者:行者123 更新时间:2023-11-30 00:04:51 25 4
gpt4 key购买 nike

假设有一个表 tableX,如下所示:

|     date    | hours |
| 2014-07-02 | 10 |
| 2014-07-03 | 10 |
| 2014-07-07 | 20 |
| 2014-07-08 | 40 |

日期为“工作日”——即没有周末或节假日。

我想找到连续工作日之间的工作时间增加情况,如下所示:

|     date    | hours |
| 2014-07-03 | 0 |
| 2014-07-07 | 10 |
| 2014-07-08 | 20 |

挑战在于弥补差距。如果没有间隙,就像

SELECT t1.date1 AS 'first day', t2.date1 AS 'second day', (t2.hours - t1.hours) 
FROM tableX t1
LEFT JOIN tableX t2 ON t2.date1 = DATE_add(t1.date1, INTERVAL 1 DAY)
ORDER BY t2.date1;

可以完成,但在本例中不起作用,因为 2014-07-03 和 2014-07-07 之间存在差距。

最佳答案

只需使用相关子查询即可。您有两个字段,因此可以使用两个相关子查询或使用 join 返回表的相关子查询来执行此操作。这是第一个版本:

SELECT t1.date1 as `first day`,
(select t2.date1
from tableX t2
where t2.date1 > t.date1
order by t2.date asc
limit 1
) as `next day`,
(select t2.hours
from tableX t2
where t2.date1 > t.date1
order by t2.date asc
limit 1
) - t.hours
FROM tableX t
ORDER BY t.date1;

关于mysql - 使用 SQL 查找先前的、不连续的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24663788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com