我需要计算MySQL中两个日期之间的差异(以天为单位),不包括周末(星期六和星期日)。也就是说,天数差减去两者之间的周六和周日数。
目前,我只是使用以下方法计算天数:
SELECT DATEDIFF('2012-03-18', '2012-03-01')
此收益17,但我想排除周末,所以我想12(因为第3和4、10、11和17日是周末)。
17
12
我不知道从哪里开始。我知道该WEEKDAY()功能和所有相关功能,但是我不知道如何在此上下文中使用它们。
WEEKDAY()
插图:
mtwtfSSmtwtfSS 123456712345 one week plus 5 days, you can remove whole weeks safely 12345------- you can analyze partial week's days at start date -------12345 or at ( end date - partial days )
伪代码:
@S = start date @E = end date, not inclusive @full_weeks = floor( ( @E-@S ) / 7) @days = (@E-@S) - @full_weeks*7 OR (@E-@S) % 7 SELECT @full_weeks*5 -- not saturday+sunday +IF( @days >= 1 AND weekday( S+0 )<=4, 1, 0 ) +IF( @days >= 2 AND weekday( S+1 )<=4, 1, 0 ) +IF( @days >= 3 AND weekday( S+2 )<=4, 1, 0 ) +IF( @days >= 4 AND weekday( S+3 )<=4, 1, 0 ) +IF( @days >= 5 AND weekday( S+4 )<=4, 1, 0 ) +IF( @days >= 6 AND weekday( S+5 )<=4, 1, 0 ) -- days always less than 7 days