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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…