MySQL计算日期工作日差
时间: 2023-09-24 21:04:26 浏览: 195
您好!要计算MySQL中两个日期之间的工作日差,可以使用如下方法:
- 创建一个名为
dates
的临时表,其中包含要比较的两个日期之间的所有日期。可以使用以下查询来生成该表:
CREATE TABLE dates (date_value DATE);
INSERT INTO dates (date_value)
SELECT DATE_ADD(start_date, INTERVAL seq DAY)
FROM
(SELECT MIN(date1) AS start_date, MAX(date2) AS end_date
FROM (
SELECT '2022-01-01' AS date1, '2022-01-10' AS date2 -- 替换为你要比较的日期范围
UNION ALL
SELECT '2022-01-10', '2022-01-01'
) AS temp) AS temp2
JOIN
(SELECT 0 AS seq UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7
UNION ALL SELECT 8 UNION ALL SELECT 9) AS temp3
WHERE DATE_ADD(start_date, INTERVAL seq DAY) <= end_date;
在上面的查询中,将 '2022-01-01'
和 '2022-01-10'
替换为您要比较的实际日期范围。
- 然后,可以使用以下查询计算工作日差:
SELECT COUNT(*)
FROM dates
WHERE WEEKDAY(date_value) NOT IN (5, 6); -- 排除周六和周日
这将返回两个日期之间的工作日差。
请注意,上述方法假设周六和周日为非工作日。如果您的工作日定义不同,请相应地调整查询中的条件。
希望对您有所帮助!如果您有任何疑问,请随时提问。
相关推荐















