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

来源:互联网 发布:淘宝模板大寸好吗 编辑:程序博客网 时间:2024/06/05 09:08

-- 设定日期表起止参数
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);

0 0
原创粉丝点击