你最容易计算多少例如星期一是用一个月的MySQL(今天算)?
在一次查询中解决一周中所有日子的解决方案的奖励积分。
期望的输出(2010年8月17日星期二):
dayOfWeek left
1 2 -- Sunday
2 2 -- Monday
3 3 -- Tuesday (yep, including today)
4 2 -- Wednesday
5 2 -- Thursday
6 2 -- Friday
7 2 -- Saturday
答案 0 :(得分:1)
我找到了什么
根据这篇文章“寻找下一个星期一”
http://www.gizmola.com/blog/archives/99-Finding-Next-Monday-using-MySQL-Dates.html
SELECT DATE_ADD(CURDATE(), INTERVAL (9 - IF(DAYOFWEEK(CURDATE())=1, 8,
DAYOFWEEK(CURDATE()))) DAY) AS NEXTMONDAY;
我们需要做的是计算月末和下周一之间的天数, 除以7。
所以结果如下:
周一
SELECT CEIL( ((DATEDIFF(LAST_DAY(NOW()),DATE_ADD(CURDATE(),
INTERVAL (9 - IF(DAYOFWEEK(CURDATE())=1, 8, DAYOFWEEK(CURDATE()))) DAY)))+1)/7)
+ IF(DAYOFWEEK(CURDATE())=2,1,0)
周二:
SELECT CEIL( ((DATEDIFF(LAST_DAY(NOW()),DATE_ADD(CURDATE(),
INTERVAL (10 - IF(DAYOFWEEK(CURDATE())=1, 8, DAYOFWEEK(CURDATE()))) DAY)))+1)/7)
+ IF(DAYOFWEEK(CURDATE())=3,1,0)
答案 1 :(得分:1)
创建一个日期表,其中包含您关注的每一天的一行(例如2000年1月1日 - 2099年12月31日):
create table dates (the_date date primary key);
delimiter $$
create procedure populate_dates (p_start_date date, p_end_date date)
begin
declare v_date date;
set v_date = p_start_date;
while v_date <= p_end_date
do
insert ignore into dates (the_date) values (v_date);
set v_Date = date_add(v_date, interval 1 day);
end while;
end $$
delimiter ;
call populate_dates('2000-01-01','2099-12-31');
然后你可以运行这样的查询来获得你想要的输出:
set @date = curdate();
select dayofweek(the_date) as dayOfWeek, count(*) as numLeft
from dates
where the_date >= @date
and the_date < str_to_date(period_add(date_format(@date,'%Y%m'),1),'%Y%m')
group by dayofweek(the_date);
这将排除本月剩余0次发生的星期几。如果你想看到那些你可以用一周中的几天创建另一个表(1-7):
create table days_of_week (
id tinyint unsigned not null primary key,
name char(10) not null
);
insert into days_of_week (id,name) values (1,'Sunday'),(2,'Monday'),
(3,'Tuesday'),(4,'Wednesday'),(5,'Thursday'),(6,'Friday'),(7,'Saturday');
并使用左连接查询该表连接到日期表:
select w.id, count(d.the_Date) as numLeft
from days_of_week w
left outer join dates d on w.id = dayofweek(d.the_date)
and d.the_date >= @date
and d.the_date < str_to_date(period_add(date_format(@date,'%Y%m'),1),'%Y%m')
group by w.id;
答案 2 :(得分:0)
看看我的回复;
MySQL: Using the dates in a between condition for the results
和
Select all months within given date span, including the ones with 0 values
对于我认为可以很好地工作的方式,类似于上面的@Walker,但是不必在查询中执行dayofweek()函数,也可能更灵活。其中一个响应有一个链接到我的表的SQL转储,如果它有帮助就可以导入!