Last Friday of the month in MySQL

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

Thanks in advance.

to change. Hi Stefan. This is what I did

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 would like to know if there is a more reasonable way.

EDIT. I did some test bases on samplebias answer to find the last Monday, Tuesday, etc. A certain 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 this helps someone else. Thanks again samplebias .;)

+2
source share
2 answers

Here is a simplified version using only date math:

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

, NOW() ( ), NOW() , LAST_DAY(var), , NOW().

+8
-- 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
+1

All Articles