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

Tæl dage mellem to datoer, eksklusive weekender (kun MySQL)

Prøv det blot ved at bruge en simpel funktion :

CREATE FUNCTION TOTAL_WEEKDAYS(date1 DATE, date2 DATE)
RETURNS INT
RETURN ABS(DATEDIFF(date2, date1)) + 1
     - ABS(DATEDIFF(ADDDATE(date2, INTERVAL 1 - DAYOFWEEK(date2) DAY),
                    ADDDATE(date1, INTERVAL 1 - DAYOFWEEK(date1) DAY))) / 7 * 2
     - (DAYOFWEEK(IF(date1 < date2, date1, date2)) = 1)
     - (DAYOFWEEK(IF(date1 > date2, date1, date2)) = 7);
 

Test:

SELECT TOTAL_WEEKDAYS('2013-08-03', '2013-08-21') weekdays1,
       TOTAL_WEEKDAYS('2013-08-21', '2013-08-03') weekdays2;
 

Resultat:

| WEEKDAYS1 | WEEKDAYS2 | ------------------------- | 13 | 13 |

  1. PostgreSQL Planet i Ansible Galaxy

  2. Lær MySQL – Ny teknologiuge

  3. Upsert med en transaktion

  4. Brug af Microsoft DiskSpd til at teste dit lagerundersystem