喂。如何使用mysql获取当月最后一个星期五的日期?
提前致谢。
修改。嗨Stefan。这就是我所做的
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
但我想知道是否有更聪明的方式。
EDIT。我在samplebias上做了一些测试,找到了特定月份的最后一个星期一,星期二等等。
这些是正确的查询。
-- 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
希望它可以帮助别人。 再次感谢samplebias。 ;)
答案 0 :(得分:8)
以下是仅使用日期数学的简化版本:
SELECT LAST_DAY(NOW()) - ((7 + WEEKDAY(LAST_DAY(NOW())) - 4) % 7);
根据NOW()
的计算方式(每个语句一次或两次),您可能仍希望将其包装在函数中并将NOW()
的结果存储到变量中,然后使用该变量对于LAST_DAY(var)
来电,以避免在月份在NOW()
来电之间滚动的竞争条件。
答案 1 :(得分:1)
-- 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