我需要使用
mysql查找两个日期之间的星期日数.我知道如何使用
PHP但我需要使用mysql进行计算. 最佳答案
SET @START_DATE = '2014-01-22';
SET @END_DATE = '2014-06-29';
SELECT
ROUND((
(unix_timestamp(@END_DATE) - unix_timestamp(@START_DATE) ) /(24*60*60)
-7+WEEKDAY(@START_DATE)-WEEKDAY(@END_DATE)
)/7)
+ if(WEEKDAY(@START_DATE) <= 6, 1, 0)
+ if(WEEKDAY(@END_DATE) >= 6, 1, 0) as Sundays;
解决方案包括两部分:
>计算完整周的数量(圆形部分),显然你将在7周内有7个星期日.
>计算非完整周部分(第一个或最后一个)中包含的天数
如果您需要多次使用它,可以将其包装到函数中:
DROP function IF EXISTS `count_weekdays`;
DELIMITER $$
CREATE FUNCTION `count_weekdays` (startDate date, endDate date, wd int)
RETURNS INTEGER
BEGIN
RETURN ROUND((
(unix_timestamp(endDate) - unix_timestamp(startDate) ) /(24*60*60)
-7+WEEKDAY(startDate)-WEEKDAY(endDate)
)/7)
+ if(WEEKDAY(startDate) <= wd, 1, 0)
+ if(WEEKDAY(endDate) >= wd, 1, 0);
END$$
DELIMITER ;
然后你就可以像这样使用它:
SET @START_DATE = '2018-07-03';
SET @END_DATE = '2018-07-28';
select
count_weekdays(@START_DATE, @END_DATE, 6) as Sundays,
count_weekdays(@START_DATE, @END_DATE, 5)
+ count_weekdays(@START_DATE, @END_DATE, 6) as weekends;
其中6~工作日的数字代表星期日,5~星期六.