In mysql How to find number of sundays in a month - mysql

In mysql how to find number of sundays in month by usnig month in where clause
Ex:
month(log_date)=month(now());
month(log_date) = 12;
output: 5 sundays

Possible way to do it which avoids using any tables. This finds the number of days in the month, and depending on that and what day of the week the last day is then it just returns a value
SELECT CASE DAYOFMONTH(LAST_DAY(NOW()))
WHEN 31 THEN
CASE DAYOFWEEK(LAST_DAY(NOW()))
WHEN 1 THEN 5
WHEN 2 THEN 5
WHEN 3 THEN 5
ELSE 4
END
WHEN 30 THEN
CASE DAYOFWEEK(LAST_DAY(NOW()))
WHEN 1 THEN 5
WHEN 2 THEN 5
ELSE 4
END
WHEN 29 THEN
CASE DAYOFWEEK(LAST_DAY(NOW()))
WHEN 1 THEN 5
ELSE 4
END
ELSE 4
END

SQL query for get total sunday in given month from DB
USE BETWEEN :- BETWEEN operator selects values within a given range.
Note :- DAYOFWEEK actually returns 1 for Sunday
SELECT count(*) AS total_sunday FROM `table` WHERE DAYOFWEEK(`date`) = 1 BETWEEN '2017-11-01' AND '2017-11-30';

In mysql just copy and paste the query given below. It will give you number of Sundays in current month.
WITH RECURSIVE offdays as(
SELECT
LAST_DAY(CURDATE()-INTERVAL 1 MONTH) + INTERVAL 1 DAY AS `Date`,
DAYNAME(LAST_DAY(CURDATE()-INTERVAL 1 MONTH) + INTERVAL 1 DAY) AS `DayName`
UNION ALL
SELECT `Date` + INTERVAL 1 DAY, DAYNAME(`Date` + INTERVAL 1 DAY)
FROM offdays WHERE `DATE` < LAST_DAY(CURDATE())
) SELECT count(*) FROM offdays where DAYNAME(DATE) = 'Sunday';
you will get number of sundays in current month. Just replace the CURDATE() with any date. The query will give you the number of Sundays of the month of the date supplied.

Try this function, you use like
count_days_in_month($date_month,$day_idx);
$day_idx is 1 - 7 where Sunday is 1, Saturday is 7
eg.
select count_days_in_month('2020-02-01',1);
delimiter //
create or replace function count_days_in_month(input_date DATE,dayindex INT)
returns INT
DETERMINISTIC
BEGIN
declare start_day_idx INT default (select dayofweek( date_sub(input_date,INTERVAL (DAYOFMONTH(input_date)-1) DAY )) from dual);
declare days_in_month INT default (SELECT dayofmonth(LAST_DAY(input_date)));
declare days_over_28 INT default (days_in_month-28);
if days_in_month > 28 then
if (days_over_28 > (dayindex-start_day_idx)) and ((dayindex-start_day_idx) >= 0) then
return 5;
else
return 4;
end if;
else
return 4;
end if;
END//
Eg to test the count of all days in a month:
select
count_days_in_month('2020-02-01',1) 'Sun',
count_days_in_month('2020-02-01',2) 'Mon',
count_days_in_month('2020-02-01',3) 'Tue',
count_days_in_month('2020-02-01',4) 'Wed',
count_days_in_month('2020-02-01',5) 'Thur',
count_days_in_month('2020-02-01',6) 'Fri',
count_days_in_month('2020-02-01',7) 'Sat'
from
dual;//

Related

MYSQL: Getting all results from last week starting Monday)

CREATE TABLE `sport_data` (
`id` int(255) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`sport` varchar(255) NOT NULL,
`musclePlan` varchar(255) NOT NULL,
`sport_time` varchar(255) NOT NULL,
`kcal` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
How can i get all data from this table from the last week (from Monday to Sunday)?
I have tried:
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+5 DAY AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-2 DAY
I don't know if this is correct that way?
Thanks in advance.
The >= and < pattern is what we usually use. That part looks right.
I think the question is about the expressions that returning the range start and end values.
I suggest that we test those expressions for a variety of date values, not just CURDATE(). We can use a value in place of CURDATE(), and check the results, and do that for a series of date values.
Conveniently, those expressions will evaluate the same in a SELECT list as they do in a WHERE clause. So we can run a SELECT statement, and check the results.
For example:
SELECT t.dt AS dt
, t.dt - INTERVAL DAYOFWEEK(t.dt)+5 DAY AS _ge
, t.dt - INTERVAL DAYOFWEEK(t.dt)-2 DAY AS _lt
FROM (
SELECT CURDATE() + INTERVAL 0 DAY AS dt
UNION ALL SELECT CURDATE() + INTERVAL -1 DAY
UNION ALL SELECT CURDATE() + INTERVAL -2 DAY
UNION ALL SELECT CURDATE() + INTERVAL -3 DAY
UNION ALL SELECT CURDATE() + INTERVAL -4 DAY
UNION ALL SELECT CURDATE() + INTERVAL -5 DAY
UNION ALL SELECT CURDATE() + INTERVAL -6 DAY
UNION ALL SELECT CURDATE() + INTERVAL -7 DAY
UNION ALL SELECT CURDATE() + INTERVAL -8 DAY
UNION ALL SELECT CURDATE() + INTERVAL -9 DAY
UNION ALL SELECT CURDATE() + INTERVAL -10 DAY
) t
If the expressions are returning the values we expect, in accordance with the specification, for each possible date value, then the expressions are right.
If the expressions are returning values that don't meet the spec, then we need to make adjustments. Note that an expression that "works" on a Wednesday date might not "work" on a Sunday date.)
DEMO: Showing 3 approaches and why current doesn't work.
If we assume by "last week" you mean the last full week Monday - Sunday of a week prior to the day you're presently on...
So if today was 20180422, you'd want 20180409-20180415
SELECT *
FROM SO50026532_sport_data
CROSS JOIN (SELECT #Today:=curdate()) z
WHERE date >= #today - interval (6 + case when dayofweek(#today)=1 then 7 else dayofWeek(#today)-1 end) day
and date <=#today - interval (case when dayofweek(#today)=1 then 7 else dayofWeek(#today)-1 end) day;
Or if your a fan of the >= and < then
SELECT *
FROM SO50026532_sport_data
CROSS JOIN (SELECT #Today:=curdate()) z
WHERE date >= #today - interval (6 + case when dayofweek(#today)=1 then 7 else dayofWeek(#today)-1 end) day
and date <#today - interval (case when dayofweek(#today)=1 then 7 else dayofWeek(#today)-1 end-1) day;
in the 2nd example we had to subtract by 1 since dayofweek isn't a 0 based. Of course I could have just date shifted everything down 2 and set sunday to 6... then I wouldn't' need to subtract by 1. and then we'd be adding 7 instead of 6 on the 1st part of the where. (demo has these 3 and your initial example showing what happens on 4/22.
Dayofweek starts on Sunday being 1. So I use a case statement to shift 1 to 7 and and all the others down 1 giving us Monday = 1 and sunday = 7
The cross join to derived table z was so I could control the curdate() easier and test. You could replace the variable with curdate() if you want and eliminate the cross join and derived table.
The first where clause subtracts 6 days (1 week and then the # of days from current date back to monday. This ensures we always start 1 week back from current date and on a monday. then we only get dates to the Sunday of that week.

Grouping COUNT by Time in MySql

I have a simple query that give me the count of application types; it looks something like this:
SELECT Application_Type, COUNT(*) FROM Loan_Applications GROUP BY Application_Type;
It returns something like this:
Home 3
Car 21
Commercial 16
There is a field in the database called Submission_Date (Of type Date)
How can I query and break up this data by week?
Type This week Last week 2 weeks ago
Home 1 1 1
Car 9 6 6
Commercial 10 0 3
You can try something like:
SELECT
Application_Type,
SUM(IF(Submission_Date BETWEEN CURRENT_DATE AND CURRENT_DATE - INTERVAL 1 WEEK, 1, 0)) AS 'This week',
SUM(IF(Submission_Date BETWEEN CURRENT_DATE- INTERVAL 1 WEEK AND CURRENT_DATE - INTERVAL 2 WEEK, 1, 0)) AS 'Last week',
SUM(IF(Submission_Date BETWEEN CURRENT_DATE- INTERVAL 2 WEEK AND CURRENT_DATE - INTERVAL 3 WEEK, 1, 0)) AS '2 weeks ago',
FROM Loan_Applications
GROUP BY Application_Type
;
Or:
SET #date1w = CURRENT_DATE - INTERVAL 1 WEEK;
SET #date2w = CURRENT_DATE - INTERVAL 2 WEEK;
SET #date3w = CURRENT_DATE - INTERVAL 3 WEEK;
SELECT
Application_Type,
SUM(IF(Submission_Date BETWEEN CURRENT_DATE AND #date1w, 1, 0)) AS 'This week',
SUM(IF(Submission_Date BETWEEN #date1w AND #date2w, 1, 0)) AS 'Last week',
SUM(IF(Submission_Date BETWEEN #date2w AND #date3w, 1, 0)) AS '2 weeks ago',
FROM Loan_Applications
GROUP BY Application_Type
;
You can make a SUMIF type of calculation. The following sums the number of rows where the submission date is within the last week.
SUM(CASE WHEN submission_date >= CURDATE() - 7 THEN 1 ELSE 0 END)
You could then repeat this for different ranges, to get any "bands" that you desire.
Try
SELECT
Application_Type,
SUM(WEEKOFYEAR(Submission_Date) = WEEKOFYEAR(NOW())) AS `This week`,
SUM(WEEKOFYEAR(Submission_Date) = WEEKOFYEAR(DATE_ADD(NOW(),INTERVAL -1 WEEK))) AS `Last week`,
SUM(WEEKOFYEAR(Submission_Date) = WEEKOFYEAR(DATE_ADD(NOW(),INTERVAL -2 WEEK))) AS `2 weeks ago`
FROM Loan_Applications GROUP BY Application_Type;
;
it is based on the fact that SUM of a boolean expression in the group by will count the cases when the expression is true

case when query in mysql

I want to execute below query,
when date diff is greater than 1 , how to add that in when clause as diffdate is not available there.
select
CASE (
SELECT DATEDIFF('2014-11-30','2015-11-29') AS DiffDate
)
WHEN 1 THEN "1 Day"
WHEN 7 THEN "Week"
WHEN ??? THEN "Yearly"
END;
Use an else
select CASE DATEDIFF('2014-11-30','2015-11-29')
WHEN 1 THEN '1 Day'
WHEN 7 THEN '7 Days'
ELSE 'Yearly'
END;

How to calculate number of Sundays between two dates using mysql

I need to find number of Sundays between two dates using mysql. I know how to do it using PHP But i need it to be calculated using mysql.
SET #START_DATE = '2014-01-22';
SET #END_DATE = '2014-06-29';
SELECT
ROUND((
(unix_timestamp(#END_DATE) - unix_timestamp(#START_DATE) ) /(24*60*60)
-7+WEEKDAY(#START_DATE)-WEEKDAY(#END_DATE)
)/7)
+ if(WEEKDAY(#START_DATE) <= 6, 1, 0)
+ if(WEEKDAY(#END_DATE) >= 6, 1, 0) as Sundays;
Solution consist of 2 parts:
counts number of full weeks (ROUND part), obviously you'll have 7 Sundays in 7 weeks.
count days that are included into the not full week parts (first or last)
If you'll need to use it more than once you can wrap it into the function:
DROP function IF EXISTS `count_weekdays`;
DELIMITER $$
CREATE FUNCTION `count_weekdays` (startDate date, endDate date, wd int)
RETURNS INTEGER
BEGIN
RETURN ROUND((
(unix_timestamp(endDate) - unix_timestamp(startDate) ) /(24*60*60)
-7+WEEKDAY(startDate)-WEEKDAY(endDate)
)/7)
+ if(WEEKDAY(startDate) <= wd, 1, 0)
+ if(WEEKDAY(endDate) >= wd, 1, 0);
END$$
DELIMITER ;
Then you will be able to use it like this:
SET #START_DATE = '2018-07-03';
SET #END_DATE = '2018-07-28';
select
count_weekdays(#START_DATE, #END_DATE, 6) as Sundays,
count_weekdays(#START_DATE, #END_DATE, 5)
+ count_weekdays(#START_DATE, #END_DATE, 6) as weekends;
Where 6 ~ number of weekday stands for Sunday, 5 ~ Saturday.
http://sqlfiddle.com/#!2/d41d8/50695
Maybe there will be no code on this link someday so I posted it here.
the upper link will show the number of the day and with date of the sundays. if you want to find any other day change the 1 at last to 2 for monday
select DATE_ADD('2012-12-15', INTERVAL ROW DAY) as Date,
row+1 as DayOfMonth from (
SELECT #row := #row + 1 as row FROM
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6) t1,
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6) t2,
(SELECT #row:=-1) t3 limit 31
) b
where
DATE_ADD('2012-12-01', INTERVAL ROW DAY)
between '2012-12-01' and '2012-12-31'
and
DAYOFWEEK(DATE_ADD('2012-12-01', INTERVAL ROW DAY))=1
Does this work...
SELECT FLOOR(
(DATEDIFF(
'#enddate'
,'#startdate' + INTERVAL
LENGTH(SUBSTRING_INDEX('654321',WEEKDAY('#startdate'),1))
DAY) + 1)/7) + 1 x;
SELECT a.StartDate, a.EndDate,
(DAY(EndDate - StartDate) / 7)
+ iif(DAY(EndDate - StartDate)%7 + DATEPART(DW, StartDate) > 8 , 1, 0)
Sundays FROM
(SELECT GETDATE() StartDate, DATEADD(DAY, 11, GETDATE()) EndDate) a
This is useful for multiple start and end dates in a table.
no need of variables and loops!
How it works: determines the number of full weeks between start and end date,
determines the days less than a week and add with the start day index(1,2,3,4,5,6,7) if that value Greater than count 8(means which is Sunday !)
For Sunday week day index is 1, day 8 is nothing but index 1.
SELECT COUNT(*) FROM table_name
WHERE column BETWEEN 'start_date' AND 'end_date'
AND WEEKDAY(date) = 6;
Refer this, mysql have a function dayofweek, you can easily calculate starting week day and after that divide the number of days with 7:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek
OR
SELECT COUNT(*) FROM table_name
WHERE date_column_of_table_name BETWEEN '2013-01-11' AND '2013-03-01'
AND WEEKDAY(date_column_of_table_name) = 6
Try this
select count(DAYNAME(your_date_field)='Sunday') as sunday from tbl_name where your_date_field between 'date1' AND 'date2'

MySQL Query to select data from last week?

Hi I have a table with a date field and some other information.
I want to select all entries from the past week, (week start from Sunday).
table values:
id date
2 2011-05-14 09:17:25
5 2011-05-16 09:17:25
6 2011-05-17 09:17:25
8 2011-05-20 09:17:25
15 2011-05-22 09:17:25
I want to select all ids from last week, expected output is 5, 6, 8.
(id 2 not in last week, and id 15 is in current week.)
How to write and SQL Query for the same.
select id from tbname
where date between date_sub(now(),INTERVAL 1 WEEK) and now();
SELECT id FROM tbl
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
SELECT id FROM table1
WHERE YEARWEEK(date) = YEARWEEK(NOW() - INTERVAL 1 WEEK)
I use the YEARWEEK function specifically to go back to the prior whole calendar week (as opposed to 7 days before today). YEARWEEK also allows a second argument that will set the start of the week or determine how the first/last week of the year are handled. YEARWEEK lets you to keep the number of weeks to go back/forward in a single variable, and will not include the same week number from prior/future years, and it's far shorter than most of the other answers on here.
Simplified form:
Last week data:
SELECT id FROM tbl
WHERE
WEEK (date) = WEEK( current_date ) - 1 AND YEAR( date) = YEAR( current_date );
2 weeks ago data:
SELECT id FROM tbl
WHERE
WEEK (date) = WEEK( current_date ) - 2 AND YEAR( date) = YEAR( current_date );
SQL Fiddle
http://sqlfiddle.com/#!8/6fa6e/2
You can make your calculation in php and then add it to your query:
$date = date('Y-m-d H:i:s',time()-(7*86400)); // 7 days ago
$sql = "SELECT * FROM table WHERE date <='$date' ";
now this will give the date for a week ago
Probably the most simple way would be:
SELECT id
FROM table
WHERE date >= current_date - 7
For 8 days (i.e. Monday - Monday)
PLEASE people... 'Last week' like the OP asked and where I was looking for (but found none of answers satisfying) is THE LAST WEEK.
If today is Tuesday, then LAST WEEK is Monday A WEEK AGO to Sunday A WEEK AGO.
So:
WHERE
WEEK(yourdate) = WEEK(NOW()) - 1
Or for ISO weeks:
WHERE
WEEK(yourdate, 3) = WEEK(NOW(), 3) - 1
If you're looking to retrieve records within the last 7 days, you can use the snippet below:
SELECT date FROM table_name WHERE DATE(date) >= CURDATE() - INTERVAL 7 DAY;
Here is a way to get last week, month, and year records in MySQL.
Last Week
SELECT UserName, InsertTime
FROM tblaccounts
WHERE WEEK(InsertTime) = WEEK(NOW()) - 1
AND MONTH(InsertTime) = MONTH(NOW())
AND YEAR(InsertTime) = YEAR(NOW())
Last Month
SELECT UserName, InsertTime
FROM tblaccounts
WHERE MONTH(InsertTime) = MONTH(NOW()) - 1
AND YEAR(InsertTime) = YEAR(NOW())
Last YEAR
SELECT UserName, InsertTime
FROM tblaccounts
WHERE YEAR(InsertTime) = YEAR(NOW()) - 1;
You'll need to calc which day relative to today is Sunday in your middleware (php, python, etc.)*
Then,
select id
from table
where date >= "$sunday-date" + interval 7 DAY
may be a way to get sunday's date relative to today in MySQL as well; that would be arguably the cleaner solution if not too expensive to perform
It can be in a single line:
SELECT * FROM table WHERE Date BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW()
A simple way can be this one, this is a real example from my code and works perfectly:
where("actions.created_at >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK)")
For more example Like last month, last year, last 15 days, last 3 months
Fetch Last WEEK Record
Using the below MySQL query for fetching the last week records from the mysql database table.
SELECT name, created_at
FROM employees
WHERE
YEARWEEK(`created_at`, 1) = YEARWEEK( CURDATE() - INTERVAL 1 WEEK, 1)
The above query will not work.
After the where clause, if we can not CAST the column value, then it will not work. You should cast the column value.
e.g.:
SELECT.....
WHERE CAST( yourDateColumn AS DATE ) > DATEADD( DAY, -7, CAST( GETDATE() AS DATE )
SELECT id FROM tb1
WHERE
YEARWEEK (date) = YEARWEEK( current_date -interval 1 week )
I often do a quick "last week" check as well and the following tends to work well for me and includes today.
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
SET #StartDate = Getdate() - 7 /* Seven Days Earlier */
SET #EndDate = Getdate() /* Now */
SELECT id
FROM mytable
WHERE date BETWEEN #StartDate AND #Enddate
If you want this to NOT include today just subtract an extra day from the #EndDate. If I select these two variables today get
#StartDate 2015-11-16 16:34:05.347 /* Last Monday */
#EndDate 2015-11-23 16:34:05.347 /* This Monday */
If I wanted Sunday to Sunday I would have the following.
SET #StartDate = Getdate() - 8 /* Eight Days Earlier */
SET #EndDate = Getdate() - 1 /* Yesterday */
#StartDate 2015-11-15 16:34:05.347 /* Previous Sunday */
#EndDate 2015-11-22 16:34:05.347 /* Last Sunday */
WHERE yourDateColumn > DATEADD(DAY, -7, GETDATE()) ;
You can also use it esay way
SELECT *
FROM inventory
WHERE YEARWEEK(`modify`, 1) = YEARWEEK(CURDATE(), 1)
i Use this for the week start from SUNDAY:
SELECT id FROM tbl
WHERE
date >= curdate() - INTERVAL DAYOFWEEK(curdate())+5 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-2 DAY
try this
WHERE trunc(DATE) <= (trunc (sysdate) -5) AND trunc(DATE) >= (trunc (sysdate) -12)
-5 is 5 days back from system date ,, -12 is 12 days back from system date for this example wednesday / or sednesday to wednesday cant recall.
Try this:
Declare #Daytype varchar(15),
#StartDate datetime,
#EndDate datetime
set #Daytype = datename(dw, getdate())
if #Daytype= 'Monday'
begin
set #StartDate = getdate()-7
set #EndDate = getdate()-1
end
else if #Daytype = 'Tuesday'
begin
set #StartDate = getdate()-8
set #EndDate = getdate()-2
end
Else if #Daytype = 'Wednesday'
begin
set #StartDate = getdate()-9
set #EndDate = getdate()-3
end
Else if #Daytype = 'Thursday'
begin
set #StartDate = getdate()-10
set #EndDate = getdate()-4
end
Else if #Daytype = 'Friday'
begin
set #StartDate = getdate()-11
set #EndDate = getdate()-5
end
Else if #Daytype = 'Saturday'
begin
set #StartDate = getdate()-12
set #EndDate = getdate()-6
end
Else if #Daytype = 'Sunday'
begin
set #StartDate = getdate()-13
set #EndDate = getdate()-7
end
select #StartDate,#EndDate
You can try this one. it worked for me :
where date(createdtime) <= date(curdate())-7
In the the above code createdtime is database field name, as individuals this name could vary.
If you already know the dates then you can simply use between, like this:
SELECT id
FROM `Mytable`
where MyDate BETWEEN "2011-05-15" AND "2011-05-21"