月份剩余的星期一数量

Veg*_*sen 5 mysql

您如何最容易地计算使用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
Run Code Online (Sandbox Code Playgroud)

Ike*_*ker 2

创建一个日期表,其中包含您关心的每一天的一行(例如 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');
Run Code Online (Sandbox Code Playgroud)

然后您可以运行这样的查询来获取所需的输出:

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);
Run Code Online (Sandbox Code Playgroud)

这将排除该月中剩余出现次数为 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');
Run Code Online (Sandbox Code Playgroud)

并通过左连接到日期表来查询该表:

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;
Run Code Online (Sandbox Code Playgroud)