今天遇到运营那边有个需求,需要找出注册用户排除周六周日的每日打卡情况(包含不是周六周日的当天),当时的第一反应是想找一个能实现排除周六周日能计算到月底还有多少工作日的函数,找了半天没找到,还是自己写一个吧。我崇拜的王大哥也写了一个,贴出来和大家分享。代码如下:
- DROP FUNCTION IF EXISTS count_day_left ;
- DELIMITER //
- CREATE FUNCTION count_day_left( f_date DATETIME )
- RETURNS INT
- DETERMINISTIC
- BEGIN
- /*
- Purpose: 统计指定日期距离月底还有多少个工作日,节假日未排除,用于打卡统计的过滤函数
- Author: 飞鸿无痕
- Date: 2012-10-09
- Useage: select count_day_left('2012-09-10');
- */
- DECLARE start_day INT;
- DECLARE end_day INT;
- DECLARE count_day INT DEFAULT 0;
- DECLARE tmp_date DATE DEFAULT DATE(f_date);
- SET end_day=DAY(LAST_DAY(f_date));
- SET start_day=DAY(f_date);
- WHILE start_day<=end_day DO
- IF ( (DAYOFWEEK(tmp_date) = 1) OR (DAYOFWEEK(tmp_date) = 7)) THEN
- SET tmp_date=DATE_ADD(tmp_date,INTERVAL 1 DAY);
- SET start_day=start_day+1;
- ELSE
- SET tmp_date=DATE_ADD(tmp_date,INTERVAL 1 DAY);
- SET start_day=start_day+1;
- SET count_day=count_day+1;
- END IF;
- END WHILE;
- RETURN count_day;
- END //
- DELIMITER ;
- DROP FUNCTION IF EXISTS count_day_left;
- DELIMITER //
- CREATE FUNCTION count_day_left(f_date DATE)
- RETURNS INT
- READS SQL DATA
- BEGIN
- RETURN DATEDIFF(LAST_DAY(f_date),f_date)-(WEEK(LAST_DAY(f_date))-WEEK(f_date))*2+IF(WEEKDAY(f_date)=6,0,1)-IF(WEEKDAY(LAST_DAY(f_date))=5,1,0);
- END //
- DELIMITER ;
阅读(45253) | 评论(0) | 转发(0) |