sql >> Database teknologi >  >> RDS >> Mysql

hvordan man beregner det samlede antal lørdage og søndage mellem to datoer i mysql

Hvis du ikke har en tabel med alle datoerne mellem din startdato og slutdato (inklusive), skal du først vedtage en forespørgsel, som vil oprette alle datoer mellem dit givne datointerval (inklusive). Brug derefter WEEKDAY funktion af MySQL for at kontrollere, om dagen er 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;

ARBEJDSDEMO

Bemærk: WEEKDAY returnerer ugedagsindekset for dato (0 =mandag, 1 =tirsdag, … 6 =søndag).

EDIT:

Hvis du kun har brug for 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. Slet ved hjælp af flere tabeller og gentag tabellen i underforespørgslen

  2. hvordan bruger man mysql med asp.net?

  3. Sådan indsætter du et linjeskift i en SQL Server VARCHAR/NVARCHAR streng

  4. MYSQL Vælg MAX Date i en sammenslutningserklæring