首页 > 解决方案 > SQL:计算两个日期之间的天数

问题描述

我在 MySQL 数据库中有一个表,其中包含以下字段:

Name         From_Date   To_Date
Mr. Spencer  2018-09-01  2018-09-25

我喜欢数一下他工作的星期一。例如,结果必须是 4. 2018-09-01 到 2018-09-25,在这些日期之间有 4 个星期一(09-03、09-10、09-17、09-24)

但我不知道怎么做。也许有人可以帮助我。

标签: mysqldatebetween

解决方案


SELECT
    (DATEDIFF('2018-09-25', '2018-09-01') # Number of days between start and end
     + 7                                  # Add a week to account for first Monday
     - (9 - DAYOFWEEK('2018-09-01')) % 7) # Days between start and next Monday
                                          # (0 if the provided date is a Monday)
                                          # 9 because DAYOFWEEK() returns 2 for Mon
    DIV 7;                                # Divide by seven and ignore the remainder

推荐阅读