开发者

last friday of the month in MySQL

开发者 https://www.devze.com 2023-02-16 16:34 出处:网络
Hallo. How can I get the date of last friday of current month with mysql? Thanks in advance. edit. Hi Stefan. This is what I\'ve done

Hallo. How can I get the date of last friday of current month with mysql?

Thanks in advance.

edit. Hi Stefan. This is what I've done

set @ldom = dayofweek(last_day(curdate()));
select 
case
when @ldom = 7 then last_day(curdate()) - interval 1 day
when @ldom = 6 then last_day(curdate())
when @ldom = 5 then last_day(curdate()) - interval 6 day 
when @ldom = 4 then last_day(curdate()) - interval 5开发者_高级运维 day 
when @ldom = 3 then last_day(curdate()) - interval 4 day
when @ldom = 2 then last_day(curdate()) - interval 3 day
else last_day(curdate()) - interval 2 day
end as last_friday

but I'd like to know if there is a smarter way.

EDIT. I made some test bases on samplebias answer to find last monday,tuesday and so on of a specific month.

These are the correct queries.

-- last sunday of month
set @data = '2011-04-01'; 
select str_to_date(last_day(@data) - ((7 + weekday(last_day(@data)) - 6) % 7),"%Y%m%d") -- 2011-04-24

-- last saturday
set @data = '2011-04-01'; 
select str_to_date(last_day(@data) - ((7 + weekday(last_day(@data)) - 5) % 7),"%Y%m%d") -- 2011-04-30

-- last friday
set @data = '2011-04-01'; 
select str_to_date(last_day(@data) - ((7 + weekday(last_day(@data)) - 4) % 7),"%Y%m%d") -- 2011-04-29

-- last thursday
set @data = '2011-04-01'; 
select str_to_date(last_day(@data) - ((7 + weekday(last_day(@data)) - 3) % 7),"%Y%m%d") -- 2011-04-28

-- last wednesday
set @data = '2011-04-01'; 
select str_to_date(last_day(@data) - ((7 + weekday(last_day(@data)) - 2) % 7),"%Y%m%d") -- 2011-04-27

-- last tuesday
set @data = '2011-04-01'; 
select str_to_date(last_day(@data) - ((7 + weekday(last_day(@data)) - 1) % 7),"%Y%m%d") -- 2011-04-26

-- last monday
set @data = '2011-04-01'; 
select str_to_date(last_day(@data) - ((7 + weekday(last_day(@data))) % 7),"%Y%m%d") -- 2011-04-25

Hope that it helps someone else. Thanks again to samplebias. ;)


Here is a simplified version using just date math:

SELECT LAST_DAY(NOW()) - ((7 + WEEKDAY(LAST_DAY(NOW())) - 4) % 7);

Depending on how NOW() gets evaluated (once or twice per statement), you might want to still wrap this in a function and store the result of NOW() into a variable, and then use the variable for the LAST_DAY(var) call, to avoid a race condition where the month rolls over between calls to NOW().


-- Today is 05 April 2013

-- Get Last Friday from MySQL

SELECT DATE_FORMAT(LAST_DAY(NOW()) - ((7 + WEEKDAY(LAST_DAY(NOW())) - 4) % 7), '%Y-%m-%d') last_friday;

-- Output

last_friday  
-------------
2013-04-26
0

精彩评论

暂无评论...
验证码 换一张
取 消