如何在mysql中计算两个日期之间的星期六和星期日的总数

时间:2016-07-26 04:57:17

标签: mysql

SELECT
    floor(
        datediff('2016-08-01','2016-07-01') / 7) * 2 + (
        CASE WHEN
        IF (weekday('2016-08-01') >= 5, 4,weekday('2016-08-01')) >=
    IF (weekday('2016-07-02') >= 5, 4,weekday('2016-07-01')) 
    THEN

            IF (weekday('2016-08-01') >= 5, 4,weekday('2016-08-01')) -
            IF (weekday('2016-07-01') >= 5, 4,weekday('2016-07-01'))
        ELSE
            5 +
            IF (weekday('2016-08-01') >= 5, 4,weekday('2016-08-01')) -      
            IF (weekday('2016-07-01') >= 5, 4, weekday('2016-07-01'))
        END
    ) weekdays;

当我执行此代码时,它总是返回9我不知道我在哪里做错了请告诉我哪里做错了。在周六和周日之间给定的日期应该是10,请建议我

1 个答案:

答案 0 :(得分:1)

如果您没有包含开始日期和结束日期(包括)之间所有日期的表格,那么您需要采用一个查询,该查询将首先创建您给定日期范围(包括)之间的所有日期。然后使用student的{​​{1}}函数检查当天是WEEKDAY还是MySQL

Saturday

WORKING DEMO

注意: WEEKDAY 返回日期的工作日索引(0 =星期一,1 =星期二,... 6 =星期日)。

修改

如果您只需要Sunday

SELECT 
dateTable.Day,
DAYNAME(dateTable.Day) AS dayName
FROM 
(   SELECT ADDDATE('2016-07-01', INTERVAL @i:=@i+1 DAY) AS DAY
    FROM (
        SELECT a.a
        FROM (SELECT 0 AS a 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 a
        CROSS JOIN (SELECT 0 AS a 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 b
        CROSS JOIN (SELECT 0 AS a 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 c
    ) a
    JOIN (SELECT @i := -1) r1
    WHERE 
    @i < DATEDIFF('2016-08-01', '2016-07-01')

) AS dateTable
WHERE WEEKDAY(dateTable.Day) IN (5,6)
ORDER BY dateTable.Day;

Demo