我想问一下是否有一种聪明或简单的方法来获取MySQL的每月的第一个和最后一个工作日。换句话说,我想避免使用“周末”,而是适当地调整第一天或最后一天的时间。
例如:
For the period: 2011-05-01 till 2011-05-31 First weekday should be: 2011-05-02 and not 2011-05-01 as 2011-05-01 is Sunday. Last weekday should be: 2011-05-31 as it is Tuesday. For the period: 2011-04-01 till 2011-04-30, First weekday: 2011-04-01 Last weekday: 2011-04-29
如何定义功能FIRST_WDOM()(星期/一个月的工作日)并LAST_WDOM()采用样式LAST_DAY()?
FIRST_WDOM()
LAST_WDOM()
LAST_DAY()
DELIMITER // CREATE FUNCTION first_wdom (d DATETIME) -- First work/week day of month RETURNS DATE DETERMINISTIC BEGIN DECLARE first_dom DATE; SET first_dom = DATE_FORMAT(d, '%Y-%m-01'); RETURN first_dom + INTERVAL (CASE DAYOFWEEK(first_dom) WHEN 1 THEN 1 WHEN 7 THEN 2 ELSE 0 END) DAY; END // CREATE FUNCTION last_wdom (d DATETIME) -- Last work/week day of month RETURNS DATE DETERMINISTIC BEGIN DECLARE last_dom DATE; SET last_dom = LAST_DAY(d); RETURN last_dom - INTERVAL (CASE DAYOFWEEK(last_dom) WHEN 1 THEN 2 WHEN 7 THEN 1 ELSE 0 END) DAY; END // DELIMITER ; mysql> SELECT FIRST_WDOM('2011-05-10'), LAST_WDOM('2011-05-10'); +--------------------------+-------------------------+ | FIRST_WDOM('2011-05-10') | LAST_WDOM('2011-05-10') | +--------------------------+-------------------------+ | 2011-05-02 | 2011-05-31 | +--------------------------+-------------------------+ 1 row in set (0.01 sec)
这只是ic3b3rg答案的改编,并假定星期六和星期日为您的周末。我使用DATETIME而不是DATE作为输入类型,以避免传入时出现截断警告NOW()。
NOW()