Get sunday date between two date and last day from one month mysql - mysql

I want to get all sunday date between two dates and get last day between two date, how can i do that in mysql?
Example :
start date | end date
2017-03-01 | 2017-03-31
then the results are :
2017-03-05
2017-03-12
2017-03-19
2017-03-26
2017-03-31
Start date and end date possible to change, please advise me.
Thank you

Since you now mentioned that you don't have a table for the dates, you could approach it like this if you don't want to add a generic calendar table on your database.
declare #startdate datetime
declare #enddate datetime
DECLARE #startdateLoop datetime
select #startdate = CAST(start as DATE), #enddate = CAST(end_date as DATE) from #t
set #startdateLoop = #startdate
CREATE TABLE #tempCal
(dates datetime)
WHILE #startdateLoop != #enddate
BEGIN
INSERT INTO #tempCal
SELECT #startdateLoop
SET #startdateLoop = DATEADD(dd, 1, #startdateLoop)
END
SELECT * FROM #tempCal
WHERE dates between #startdate and #enddate and DAYOFWEEK(dates) = 1
You may turn this into a procedure if you want to.
Would still be nice if you DO HAVE a calendar table; as Tim has suggested.

MySQL has a DAYOFWEEK() function which would return 1 for any date which is a Sunday:
SELECT date_column
FROM yourTable
WHERE (date_column BETWEEN '2017-03-01' AND '2017-03-31' AND
DAYOFWEEK(date_column) = 1) OR -- any Sunday
date_column = '2017-03-31' -- or the last date in the range
I am assuming that yourTable already has dates in it. If you need help with populating a table with a range of dates, this problem has been covered well before on Stack Overflow, q.v. here:
How to populate a table with a range of dates?
Demo here:
Rextester

SELECT calender FROM calender WHERE calender.calender >='2017-03-01' AND calender.calender <='2017-03-31' AND DAYOFWEEK(calender) = 1 OR calender = '2017-03-31' Group By calender
This is #Tim Answer
Thanks Tim

Related

In Case statement update date not greater than today date

Hi as per current statement i am updating the date in table as per below statement. I want to update the date that will be not more than today date. If the date will be more than today date then it will update with today date.
Update visiting
set OriginArrvDate
WHEN DATEPART(weekday,ORDDATE)=6 THEN DATEADD(dd,3,ORDDATE)
WHEN DATEPART(weekday,ORDDATE)=7 THEN DATEADD(dd,3,ORDDATE)
WHEN DATEPART(weekday,ORDDATE)=1 THEN DATEADD(dd,2,ORDDATE)
WHEN DATEPART(weekday,ORDDATE)=2 THEN DATEADD(dd,1,ORDDATE)
ELSE ORDDATE END
where
orddate>=CONVERT(DATE,DATEADD(dd,-100,getdate()))
In above script i am trying that when after calculating the date in ( DATEADD(dd,3,ORDDATE) ) if output will be greater than today date then it will be update with today date.
Example : ORDATE is '2021-09-26' so as per current condition ORDDATE will be 2021-09-29 but i want the result after calculating the date not more than today date. So the date will be ' 2021-09-27'
If the ORDATE calculation below today date then it will be fine and not change in date required.
Thanks for your reply
UPDATE : -
As per suggestion i have add data with Script on sqlfiddle . If you review the data for visiting table for Oid 1 and 5 . Both updated data for OriginArrvDate is more than today date. I want to update the OriginArrvDate with today date when new ordDate is more than current date.
I would use a CTE which makes it very easy to test your logic by applying a CASE expression (not a CASE statement) to the output of your existing CASE expression.
;WITH x AS
(
SELECT Oid, ORDDATE, OriginArrvDate,
CalcDate = CASE DATEPART(weekday, ORDDATE)
WHEN 6 THEN DATEADD(DAY, 3, ORDDATE)
WHEN 7 THEN DATEADD(DAY, 3, ORDDATE)
WHEN 1 THEN DATEADD(DAY, 2, ORDDATE)
WHEN 2 THEN DATEADD(DAY, 1, ORDDATE)
ELSE ORDDATE END
FROM dbo.visiting
WHERE orddate >= CONVERT(DATE,DATEADD(DAY, -100, getdate()))
AND OriginArrvDate IS NULL
)
--SELECT *,
/* -- */ UPDATE x SET
OriginArrvDate = CASE
WHEN CalcDate > GETDATE() THEN GETDATE()
ELSE CalcDate END
--FROM x;
Thanks for the fiddle, but I wrote a db<>fiddle here because I couldn't get SQLFiddle to properly show the update.
In addition to using DAY instead of dd I would also make sure to always specify a table's schema.

Get difference in hours between two dates

How can I subtract two dates (entry_date from status_change_date) to get hours between them? I do this based on an IF statement where both dates are in YYYY,MM,DD 12:00:00 format
(IF Invoice_Num != next Inv_Num then entry_date - status_change_date else...
It returns an answer in days instead of hours. I also tried using minutes(entry_day) and hours(status_change_date) in Crystal after the code was done, but I still got day values.
declare #startDate datetime
declare #endDate datetime
set #startDate = '2016-12-05 08:05:00';
set #endDate = '2016-12-05 09:52:00';
select CONVERT(varchar(3),DATEDIFF(minute,#startDate, #endDate)/60) + ':' +
RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,#startDate,#endDate)%60),2)
as TotalHours
Check this example, get the hours and minutes between to datetime vars
From document TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2),
SELECT TIMESTAMPDIFF(HOUR, '2016-12-05 12:00:00', '2016-12-06 12:00:00');
This will get you 24 hours.
SQLFiddle Demo

Count first day of month between two dates

Could someone advise how I can go about counting the number of first day of month between two dates?
For example: 02/01/2015 to 05/05/2015 will count as 4.
It can be accomplished easily like this:
DECLARE #sd DATE = '02/02/2015', #ed DATE = '05/01/2015'
SELECT DATEDIFF(mm, #sd, #ed) + CASE WHEN DAY(#sd) = 1 THEN 1 ELSE 0 END
If you have a sequence of dates stored somewhere (like in a calendar table) you can easily count the dates matching the day(date) predicate. If you don't have any suitable table with a date sequence you can use a recursive common table expression to generate one on the fly like this:
declare #start date
set #start = '02/01/2015'
declare #end date
set #end = '05/05/2015'
;with dates (date) as (
select #start date
union all
select dateadd(day, 1, date) as date from dates where date < #end
)
select count(*) no_of_firsts from dates where day(date) = 1
Sample SQL Fiddle

How to get week number of the month from the date in sql server 2008

In SQL Statement in microsoft sql server, there is a built-in function to get week number but it is the week of the year.
Select DatePart(week, '2012/11/30') // **returns 48**
The returned value 48 is the week number of the year.
Instead of 48, I want to get 1, 2, 3 or 4 (week number of the month). I think the week number of the month can be achieved by modules with Month Number of this week. For e.g.
Select DATEPART(week, '2012/11/30')%MONTH('2012/11/30')
But I want to know is there other built-in functions to get WeekNumber of the month in MS SQL SERVER.
Here are 2 different ways, both are assuming the week starts on monday
If you want weeks to be whole, so they belong to the month in which they start:
So saturday 2012-09-01 and sunday 2012-09-02 is week 4 and monday 2012-09-03 is week 1 use this:
DECLARE #date date = '2012-09-01'
SELECT (day(datediff(d,0,#date)/7*7)-1)/7+1
If your weeks cut on monthchange so saturday 2012-09-01 and sunday 2012-09-02 is week 1 and monday 2012-09-03 is week 2 use this:
DECLARE #date date = '2012-09-01'
SELECT
datediff(ww,datediff(d,0,dateadd(m,datediff(m,7,#date),0)
)/7*7,dateadd(d,-1,#date))+1
I received an email from Gerald. He pointed out a flaw in the second method. This should be fixed now
I received an email from Ben Wilkins. He pointed out a flaw in the first method. This should be fixed now
DECLARE #DATE DATETIME
SET #DATE = '2013-08-04'
SELECT DATEPART(WEEK, #DATE) -
DATEPART(WEEK, DATEADD(MM, DATEDIFF(MM,0,#DATE), 0))+ 1 AS WEEK_OF_MONTH
No built-in function. It depends what you mean by week of month. You might mean whether it's in the first 7 days (week 1), the second 7 days (week 2), etc. In that case it would just be
(DATEPART(day,#Date)-1)/7 + 1
If you want to use the same week numbering as is used with DATEPART(week,), you could use the difference between the week numbers of the first of the month and the date in question (+1):
(DATEPART(week,#Date)- DATEPART(week,DATEADD(m, DATEDIFF(m, 0, #Date), 0))) + 1
Or, you might need something else, depending on what you mean by the week number.
Just look at the date and see what range it falls in.
Range 1-7 is the 1st week, Range 8-14 is the 2nd week, etc.
SELECT
CASE WHEN DATEPART(day,yourdate) < 8 THEN '1'
ELSE CASE WHEN DATEPART(day,yourdate) < 15 then '2'
ELSE CASE WHEN DATEPART(day,yourdate) < 22 then '3'
ELSE CASE WHEN DATEPART(day,yourdate) < 29 then '4'
ELSE '5'
END
END
END
END
Similar to the second solution, less code:
declare #date datetime = '2014-03-31'
SELECT DATEDIFF(week,0,#date) - (DATEDIFF(week,0,DATEADD(dd, -DAY(#date)+1, #date))-1)
Check this out... its working fine.
declare #date as datetime = '2014-03-10'
select DATEPART(week,#date) - DATEPART(week,cast(cast(year(#date) as varchar(4))+'-' + cast(month(#date) as varchar(2)) + '-01' as datetime))+1
WeekMonth = CASE WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 22 THEN '5'
WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 15 THEN '4'
WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 8 THEN '3'
WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 1 THEN '2'
ELSE '1'
END
There is no inbuilt function to get you the week number. I dont think dividing will help you anyway as the number of weeks in a month is not constant.
http://msdn.microsoft.com/en-us/library/bb675168.aspx
I guess you can divide the number(48) by 4 and take the modules of the same and project that as the week number of that month, by adding one to the result.
Here's a suggestion for getting the first and last days of the week for a month:
-- Build a temp table with all the dates of the month
drop table #tmp_datesforMonth
go
declare #begDate datetime
declare #endDate datetime
set #begDate = '6/1/13'
set #endDate = '6/30/13';
WITH N(n) AS
( SELECT 0
UNION ALL
SELECT n+1
FROM N
WHERE n <= datepart(dd,#enddate)
)
SELECT DATEADD(dd,n,#BegDate) as dDate
into #tmp_datesforMonth
FROM N
WHERE MONTH(DATEADD(dd,n,#BegDate)) = MONTH(#BegDate)
--- pull results showing the weeks' dates and the week # for the month (not the week # for the current month)
select MIN(dDate) as BegOfWeek
, MAX(dDate) as EndOfWeek
, datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, dDate), 0)), 0), dDate) as WeekNumForMonth
from #tmp_datesforMonth
group by datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, dDate), 0)), 0), dDate)
order by 3, 1
A dirty but easy one liner using Dense_Rank function. Performance WILL suffer, but effective none the less.
DENSE_RANK()over(Partition by Month(yourdate),Year(yourdate) Order by Datepart(week,yourdate) asc) as Week
Here is the query that brings the week number on whatever the startday and endday of the week it may be.
SET DATEFIRST 2
DECLARE #FROMDATE DATE='12-JAN-2015'
-- Get the first day of month
DECLARE #ALLDATE DATE=DATEADD(month, DATEDIFF(month, 0, #FROMDATE), 0)
DECLARE #FIRSTDATE DATE
;WITH CTE as
(
-- Get all dates in that month
SELECT 1 RNO,CAST(#ALLDATE AS DATE) as DATES
UNION ALL
SELECT RNO+1, DATEADD(DAY,1,DATES )
FROM CTE
WHERE DATES < DATEADD(MONTH,1,#ALLDATE)
)
-- Retrieves the first day of week, ie, if first day of week is Tuesday, it selects first Tuesday
SELECT TOP 1 #FIRSTDATE = DATES
FROM CTE
WHERE DATEPART(W,DATES)=1
SELECT (DATEDIFF(DAY,#FIRSTDATE,#FROMDATE)/7)+1 WEEKNO
For more information I have answered for the below question. Can check that.
How do I find week number of a date according to DATEFIRST
floor((day(#DateValue)-1)/7)+1
Here you go....
Im using the code below..
DATEPART(WK,#DATE_INSERT) - DATEPART(WK,DATEADD(DAY,1,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#DATE_INSERT),0)))) + 1
Try Below Code:
declare #dt datetime='2018-03-15 05:16:00.000'
IF (Select (DatePart(DAY,#dt)%7))>0
Select (DatePart(DAY,#dt)/7) +1
ELSE
Select (DatePart(DAY,#dt)/7)
There is an inbuilt option to get the week number of the year
**select datepart(week,getdate())**
You can simply get week number by getting minimum week number of month and deduct it from week number. Suppose you have a table with dates
select
emp_id, dt , datepart(wk,dt) - (select min(datepart(wk,dt))
from
workdates ) + 1 from workdates
Solution:
declare #dt datetime='2018-03-31 05:16:00.000'
IF (Select (DatePart(DAY,#dt)%7))>0
Select (DatePart(DAY,#dt)/7) +1
ELSE
Select (DatePart(DAY,#dt)/7)
declare #end_date datetime = '2019-02-28';
select datepart(week, #end_date) - datepart(week, convert(datetime, substring(convert(nvarchar, convert(datetime, #end_date), 127), 1, 8) + '01')) + 1 [Week of Month];
Here is the tried and tested solution for this query in any situation - like if 1st of the month is on Friday , then also this will work -
select (DATEPART(wk,#date_given)-DATEPART(wk,dateadd(d,1-day(#date_given),#date_given)))+1
above are some solutions which will fail if the month's first date is on Friday , then 4th will be 2nd week of the month
Logic here works as well 4.3 weeks in every month. Take that from the DATEPART(WEEK) on every month but January. Just another way of looking at things. This would also account for months where there is a 5th week
DECLARE #date VARCHAR(10)
SET #date = '7/27/2019'
SELECT CEILING(DATEPART(WEEK,#date)-((DATEPART(MONTH,#date)-1)*4.3333)) 'Week of Month'
Below will only work if you have every week of the month represented in the select list. Else the rank function will not work, but it is a good solution.
SELECT DENSE_RANK() OVER (PARTITION BY MONTH(DATEFIELD)
ORDER BY DATEPART(WEEK,DATEFIELD) ASC) AS WeekofMont
try this one
declare #date datetime = '20210928'
select convert(int,(((cast(datepart(day,#date) as decimal(4,2))/7)-(1.00/7.00))+1.00))
select datepart(week,#date)-datepart(week,dateadd(day,1,eomonth(dateadd(m,-1,#date))))+1
or
select datepart(week,#date)-datepart(week,dateadd(d,-datepart(d,#date)+1,#date))+1
steps:
1,get the first day of month
2,week of year of the date - week of year of the first day of the month
3,+1
2023-1-1 is sunday
SET DATEFIRST 1;
DECLARE #date date = '2023-1-02';
select datepart(week,#date)-datepart(week,dateadd(day,1,eomonth(dateadd(m,-1,#date))))+1
return 2
SET DATEFIRST 7;
DECLARE #date date = '2023-1-02';
select datepart(week,#date)-datepart(week,dateadd(day,1,eomonth(dateadd(m,-1,#date))))+1
return 1
Code is below:
set datefirst 7
declare #dt datetime='29/04/2016 00:00:00'
select (day(#dt)+datepart(WEEKDAY,dateadd(d,-day(#dt),#dt+1)))/7
select #DateCreated, DATEDIFF(WEEK, #DateCreated, GETDATE())

Number of e.g. Mondays left in month

How do you most easily calculate how many e.g. Mondays are left in a month using MySQL (counting today)?
Bonus points for a solution that solves it for all days of the week in one query.
Desired output (run on Tuesday August 17th 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
Create a date table that contains one row for each day that you care about (say Jan 1 2000 - Dec 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 a query like this to get your desired output:
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);
That will exclude days of the week that have 0 occurrences left in the month. If you want to see those 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');
And query that table with a left join to the dates table:
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;
i found something
according to this article "find next monday"
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;
what we need to do is calculate the days between end month and next Monday,
and divide in 7 .
update (include current day) :
so the result is like :
for Monday
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)
for Tuesday :
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)
Have a look at my responses to;
MySQL: Using the dates in a between condition for the results
and
Select all months within given date span, including the ones with 0 values
for a way I think would work nicely, similar to #Walker's above, but without having to do the dayofweek() function within the query, and possibly more flexible too. One of the responses has a link to a SQL dump of my table which can be imported if it helps!