Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

last friday of the month in MySQL

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. ;)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...