sql >> Databasteknik >  >> RDS >> Mysql

hur man beräknar totalt antal lördagar och söndagar mellan två datum i mysql

Om du inte har en tabell med alla datum mellan ditt startdatum och slutdatum (inklusive) måste du anta en fråga som skapar alla datum mellan ditt givna datumintervall (inklusive) först. Använd sedan WEEKDAY funktion för MySQL för att kontrollera om dagen är Saturday eller Sunday

SELECT 
dateTable.Day,
DAYNAME(dateTable.Day) AS dayName
FROM 
(   SELECT ADDDATE('2016-07-01', INTERVAL @i:[email protected]+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;

ARBETSDEMO

Obs! WEEKDAY returnerar veckodagsindexet för datum (0 =måndag, 1 =tisdag, … 6 =söndag).

EDIT:

Om du bara behöver count :

SELECT 
COUNT(*) AS total
FROM 
(   SELECT ADDDATE('2016-07-01', INTERVAL @i:[email protected]+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)

Demo




  1. MySQL – Databas Character Set Encoding and Collation Explained

  2. Kan inte hitta klassen [org.springframework.orm.hibernate5.LocalSessionFactoryBean] för böna med namnet 'hibernate5AnnotatedSessionFactory'

  3. Ställ in MySQL och Oracle Database Mac OS X

  4. MySQL installation