Quantity, for example. Mondays gone a month

How do you most easily calculate how many, for example, Mondays come out in a month using MySQL (counting today)?

Bonus points for a decision that solves it for all days of the week in one request.

Desired conclusion (starts on Tuesday, August 17, 2010):

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
+5
source share
3 answers

Create a date table containing one row for each day you care about (say, January 1, 2000 - December 31, 2099):

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

Then you can run such a query to get the desired result:

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

This excludes the days of the week in which 0 cases per month remain. If you want to see them, you can create another table with the days of the week (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;
+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.

update ( ):

:

       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

:

MySQL:

, , 0

for a method that I think will work well, like @Walker above, but without having to execute the dayofweek () function inside the request and possibly more flexible. One of the answers has a link to the SQL dump of my table, which can be imported if this helps!

0
source

All Articles