您的位置:首页 > 数据库 > MySQL

mysql算两个日期之间的工作日

2014-04-29 17:27 134 查看
-- 设定日期表起止参数

set @date1='2013/01/01';

set @date2='2015/12/31';

-- 建立日期表

CREATE TABLE calendar

(day DATE NOT NULL primary key,

holiday INT(11) NOT NULL DEFAULT '0'

dow int(11) not null);

truncate calendar;

-- 建立存储过程,以便循环给日期表加入数据

delimiter $$

drop procedure if exists test;

create procedure test()

begin

declare tday date;

set tday=@date1;

while (tday <= @date2) do

insert into calendar(day) values(tday);

set tday=date_add(tday,interval 1 day);

end while;

end$$

-- 调用存储过程加数据

call test();

-- 把星期几算进去

update calendar set dow=dayofweek(day)-1;

update calendar set dow=7 where dow=0;

set @date1='2014/04/01';

set @date2='2014/04/30';

-- 利用日期表来获取两个日期之间的工作日,

-- 如果hol=0,则判断是不是周6,7 是则不算,不是则算工作日数+1;

-- hol=1 是假期(不用管是不是周6,7);

-- hol=2 是工作日,工作日数+1

SELECT COUNT(*) FROM calendar

WHERE day BETWEEN @date1 AND @date2

AND ((DAYOFWEEK(day) NOT IN(1,7) AND holiday=0) or holiday=2);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: