Get first day of week T-SQL - sql

How get first day of week (Monday) where week = 6 and year = 2020 I need get 10.02.2020
eg. week 1 in 2020 is date from 06.01.2020 - 12.01.2020
week 6 in 2020 is date from 10.02.2020 - 16.02.2020

DECLARE #YEAR int = 2020;
DECLARE #WEEKSTOADD int = 6;
SET DATEFIRST 1;
SELECT
DATEADD(day,
1 - DATEPART(dw,DATEADD(week,#WEEKSTOADD,cast(cast(#YEAR as varchar(4)) + '0101' as date))),
DATEADD(week,#WEEKSTOADD,cast(cast(#YEAR as varchar(4)) + '0101' as date)))

The following code will get the date of Monday in the week of a given date regardless of the setting of DateFirst or Language:
Cast( DateAdd( day, - ( ##DateFirst + DatePart( weekday, Datum ) - 2 ) % 7, Datum ) as Date )
An example with sample data:
with SampleData as (
select GetDate() - 30 as Datum
union all
select DateAdd( day, 1, Datum )
from SampleData
where Datum < GetDate() )
select Datum,
-- 1 = Monday through 7 = Sunday.
( ##DateFirst + DatePart( weekday, Datum ) - 2 ) % 7 + 1 as WeekDay,
-- Date of Monday in the week of the supplied date.
Cast( DateAdd( day, - ( ##DateFirst + DatePart( weekday, Datum ) - 2 ) % 7, Datum ) as Date ) as Monday
from SampleData;

As per sample data you need substring() :
select t.*, substring(datnum, charindex(' ', datnum) + 1, 10) as dt
from table t
where t.week = 6;

Related

How to get 1st and 3rd Saturday and all Sunday between 2 dates using sql

Given a date range, I'd like to return all of the Saturdays and Sundays that fall within that range, with these conditions:
Include Saturdays only if their ordinal position is either the 1st or 3rd Saturday within the month they fall (not within the entire range).
Include all Sundays, along with the ordinal position of that Sunday within the month it falls.
So for example, if the start date is Aug 15, 2021 and the end date is Sep 20, 2021, the output would be:
Dates Saturday Number (in its own month)
---------- ---------------
2021-08-21 3
2021-09-04 1
2021-09-18 3
Dates Sunday Number (in its own month)
---------- ---------------
2021-08-15 3
2021-08-22 4
2021-08-29 5
2021-09-05 1
2021-09-12 2
2021-09-19 3
Then I can take the date range in total (37 days), and subtract the Sundays (6), and the 1st and 3rd Saturdays from each month (3), to end at 28.
Tried this query
DECLARE #sd DATETIME = '2021-08-15' DECLARE #ed DATETIME =
'2021-09-20'
--find first saturday WHILE DATEPART(dw, #sd)<>7 BEGIN SET #sd = DATEADD(dd,1,#sd) END
--get next saturdays ;WITH Saturdays AS (
--initial value SELECT #sd AS MyDate, 1 AS SatNo UNION ALL
--recursive part SELECT DATEADD(dd,7,MyDate) AS MyDate, CASE WHEN SatNo + 1 =6 THEN 1 ELSE SatNo+1 END AS SatNo FROM Saturdays
WHERE DATEADD(dd,7,MyDate)<=#ed
) SELECT * FROM Saturdays WHERE SatNo IN (1,3) OPTION(MAXRECURSION 0)
it does not work properly.
Also Tried this solution
Get number of weekends between two dates in SQL
for calculate week days, but I want only 1st and 3 Saturday and all Sundays
Get a calendar table; it makes this type of business problem a breeze. Here's a simpler one:
CREATE TABLE dbo.Calendar
(
TheDate date PRIMARY KEY,
WeekdayName AS (CONVERT(varchar(8), DATENAME(WEEKDAY, TheDate))),
WeekdayInstanceInMonth tinyint
);
;WITH x(d) AS -- populate with 2020 -> 2029
(
SELECT CONVERT(date, '20200101')
UNION ALL
SELECT DATEADD(DAY, 1, d)
FROM x
WHERE d < '20291231'
)
INSERT dbo.Calendar(TheDate)
SELECT d FROM x
OPTION (MAXRECURSION 0);
;WITH c AS
(
SELECT *, rn = ROW_NUMBER() OVER
(PARTITION BY YEAR(TheDate), MONTH(TheDate), WeekdayName
ORDER BY TheDate)
FROM dbo.Calendar
)
UPDATE c SET WeekdayInstanceInMonth = rn;
Now your query is easy:
DECLARE #start date = '20210815', #end date = '20210920';
SELECT Dates = TheDate,
[Saturday Number] = WeekdayInstanceInMonth
FROM dbo.Calendar
WHERE TheDate >= #start
AND TheDate <= #end
AND WeekdayName = 'Saturday'
AND WeekdayInstanceInMonth IN (1,3);
SELECT Dates = TheDate,
[Sunday Number] = WeekdayInstanceInMonth
FROM dbo.Calendar
WHERE TheDate >= #start
AND TheDate <= #end
AND WeekdayName = 'Sunday';
Results (db<>fiddle example here):
Dates Saturday Number
---------- ---------------
2021-08-21 3
2021-09-04 1
2021-09-18 3
Dates Sunday Number
---------- ---------------
2021-08-15 3
2021-08-22 4
2021-08-29 5
2021-09-05 1
2021-09-12 2
2021-09-19 3
And to get just the number 28:
DECLARE #start date = '20210815', #end date = '20210920';
SELECT DATEDIFF(DAY, #start, #end) + 1
-
(SELECT COUNT(*)
FROM dbo.Calendar
WHERE TheDate >= #start
AND TheDate <= #end
AND WeekdayName = 'Saturday'
AND WeekdayInstanceInMonth IN (1,3))
-
(SELECT COUNT(*)
FROM dbo.Calendar
WHERE TheDate >= #start
AND TheDate <= #end
AND WeekdayName = 'Sunday');
Assuming datefirst is set for Sunday:
(
day(dt) +
datepart(weekday, dateadd(dt, 1 - day(dt))) % 7
) / 7 as SaturdayNumber,
(
day(dt) - 1 +
datepart(weekday, dateadd(dt, 1 - day(dt)))
) / 7 as SundayNumber
For all dates this essentially computes a week number (0-5) within the month, relative to Saturday/Sunday.

Custom SQL Schedule to Execute Command

I need a way to run a SQL command twice a month following this logic:
Run on the Thursday following the 2nd Tuesday of the month
And
Run on the Thursday following the 4th Tuesday of the month
Is this possible?
Running this everyday will do the trick
IF (
SELECT
DATEADD(
Month,
DATEDIFF(
Month,
0,
GETDATE()
),
0
) + 6 + 7 - (
DATEPART(
Weekday,
DATEADD(
Month,
DATEDIFF(
Month,
0,
GETDATE()
),
0
)
) + (##DateFirst + 3) + 7
) % 7 + 2
) -- Thursday after SECOND tuesday IN the this month
= GETDATE()
OR (
SELECT
DATEADD(
Month,
DATEDIFF(
Month,
0,
GETDATE()
),
0
) + 6 + 21 - (
DATEPART(
Weekday,
DATEADD(
Month,
DATEDIFF(
Month,
0,
GETDATE()
),
0
)
) + (##DateFirst + 3) + 21
) % 7 + 2
) = GETDATE() -- Thursday after FOURTH tuesday IN the this month

Collapse down calendar table by grouping like fields

I have a script that generates a calendar table and fills in the public holidays and weekends for England and Wales. I would like to have the non working days as start and end periods, so taking the input
1980-04-01 00:00:00.000 Tuesday 0
1980-04-02 00:00:00.000 Wednesday 0
1980-04-03 00:00:00.000 Thursday 0
1980-04-04 00:00:00.000 Friday 1
1980-04-05 00:00:00.000 Saturday 1
1980-04-06 00:00:00.000 Sunday 1
1980-04-07 00:00:00.000 Monday 1
1980-04-08 00:00:00.000 Tuesday 0
1980-04-09 00:00:00.000 Wednesday 0
It would give the output
Start end
1980-04-03 1980-04-08
in other words, the day before the first non working day and the day after the last non working day of the group. To do this I would presumably use a min and max with a group and dateadd, but how do I go about obtaining a unique number to group each set of days by? This is using 2008 R2.
IF OBJECT_ID('tempdb.dbo.#calendar', 'U') IS NOT NULL
DROP TABLE #calendar
IF OBJECT_ID('tempdb.dbo.#easter', 'U') IS NOT NULL
DROP TABLE #easter;
-- CREATE TABLE CALENDAR
CREATE TABLE #calendar
(
[CalendarDate] DATETIME,
dayofwk varchar(20),
)
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
--INPUTS GO HERE
SET #StartDate = '01-01-1980'
SET #EndDate = '31-12-2018'
DECLARE #Startyear int
DECLARE #endyear int
set #startyear = YEAR(#StartDate)
set #endyear = YEAR(#EndDate)
WHILE #StartDate <= #EndDate
BEGIN
INSERT INTO #calendar
(
CalendarDate, dayofwk
)
SELECT
#StartDate, datename(dw,#startdate)
SET #StartDate = DATEADD(dd, 1, #StartDate)
END
---CREATE LIST OF EASTER MONDAY & GOOD FRIDAYS
create table #easter(
eastersunday_goodfriday date)
DECLARE #y int,
#EpactCalc INT,
#PaschalDaysCalc INT,
#NumOfDaysToSunday INT,
#EasterMonth INT,
#EasterDay INT
WHILE #Startyear <= #endyear
BEGIN
SET #y = #startyear
SET #EpactCalc = (24 + 19 * (#Y % 19)) % 30
SET #PaschalDaysCalc = #EpactCalc - (#EpactCalc / 28)
SET #NumOfDaysToSunday = #PaschalDaysCalc - (
(#Y + #Y / 4 + #PaschalDaysCalc - 13) % 7
)
SET #EasterMonth = 3 + (#NumOfDaysToSunday + 40) / 44
SET #EasterDay = #NumOfDaysToSunday + 28 - (
31 * (#EasterMonth / 4)
)
insert into #easter
SELECT dateadd(d,-2, CONVERT
( SMALLDATETIME,
RTRIM(#Y)
+ RIGHT('0'+RTRIM(#EasterMonth), 2)
+ RIGHT('0'+RTRIM(#EasterDay), 2) ))
insert into #easter
SELECT dateadd(d,1, CONVERT
( SMALLDATETIME,
RTRIM(#Y)
+ RIGHT('0'+RTRIM(#EasterMonth), 2)
+ RIGHT('0'+RTRIM(#EasterDay), 2) ))
SET #Startyear =#Startyear +1
end
select calendardate, dayofwk,
--NEW YEAR'S DAY
case
when day(calendardate) = 1 and month(calendardate) = 1 and dayofwk not in ('Saturday', 'sunday') then 1
when day(calendardate) between 2 and 3 and month(calendardate) = 1 and dayofwk = 'Monday' then 1
--GOOD FRIDAY, EASTER MONDAY
WHEN eastersunday_goodfriday IS NOT NULL THEN 1
--EARLY MAY BANK HOLIDAY
WHEN (datepart(weekday, CALENDARDATE) + ##DATEFIRST - 2) % 7 + 1 = 1
and (datepart(day, CALENDARDATE) - 1) / 7 + 1 = 1
AND MONTH(CALENDARDATE) = 5
THEN 1
--LATE MAY BANK HOLIDAY
WHEN (datepart(weekday, CALENDARDATE) + ##DATEFIRST - 2) % 7 + 1 = 1
and (datepart(day, CALENDARDATE) - 1) / 7 + 1 = 4
AND MONTH(CALENDARDATE) = 5
THEN 1
--LATE AUGUST BANK HOLIDAY
WHEN (datepart(weekday, CALENDARDATE) + ##DATEFIRST - 2) % 7 + 1 = 1
and (datepart(day, CALENDARDATE) - 1) / 7 + 1 = 4
AND MONTH(CALENDARDATE) = 8
THEN 1
--CHRISTMAS DAY
WHEN DAY(CalendarDate) = 25 AND MONTH(CALENDARDATE) = 12 AND dayofwk NOT IN ('SATURDAY', 'SUNDAY') THEN 1
--BOXING DAY
WHEN DAY(CalendarDate) = 26 AND MONTH(CALENDARDATE) = 12 AND dayofwk NOT IN ('SATURDAY', 'SUNDAY') THEN 1
WHEN DAY(CalendarDate) between 27 and 28 AND MONTH(CALENDARDATE) = 12 AND DAYOFWK IN ('MONDAY','TUESDAY') THEN 1
--SAT&SUN
WHEN DATENAME(DW,CALENDARDATE) IN ('SATURDAY','SUNDAY') THEN 1
ELSE 0
end as ISNONWORKINGDAY
from #calendar c
left join #easter e
on c.calendardate = e.eastersunday_goodfriday
ORDER BY C.CALENDARDATE
This seams like a typical island problem. Given what you posted you could do this:
DECLARE #table TABLE (dt DATE, isNonWorkDay BIT);
INSERT #table(dt,isNonWorkDay)
VALUES
('1980-04-01', 0),
('1980-04-02', 0),
('1980-04-03', 0),
('1980-04-04', 1),
('1980-04-05', 1),
('1980-04-06', 1),
('1980-04-07', 1),
('1980-04-08', 0),
('1980-04-09', 0);
SELECT DATEADD(DAY,-1,MIN(t.dt)), DATEADD(DAY,1,MAX(t.dt))
FROM #table t
WHERE t.isNonWorkDay = 1;
Returns: 1980-04-03, 1980-04-08
For multiple islands you could do this:
DECLARE #table TABLE (dt DATE, isNonWorkDay BIT);
INSERT #table(dt,isNonWorkDay)
VALUES
('1980-04-01', 0),
('1980-04-02', 0),
('1980-04-03', 0),
('1980-04-04', 1),
('1980-04-05', 1),
('1980-04-06', 1),
('1980-04-07', 1),
('1980-04-08', 0),
('1980-04-09', 0),
('1980-04-10', 0),
('1980-04-11', 1),
('1980-04-12', 1),
('1980-04-13', 1),
('1980-04-14', 0),
('1980-04-15', 0);
WITH x AS
(
SELECT *, rn = ROW_NUMBER() OVER (ORDER BY t.dt)
FROM #table t
),
xx AS
(
SELECT *, grouper = x.rn - ROW_NUMBER() OVER (ORDER BY x.dt)
FROM x
WHERE x.isNonWorkDay = 1
)
SELECT dtStart = DATEADD(DAY,-1,MIN(xx.dt)), dtend = DATEADD(DAY,1,MAX(xx.dt))
FROM xx
GROUP BY xx.grouper;
Returns:
dtStart dtend
---------- ----------
1980-04-03 1980-04-08
1980-04-10 1980-04-14
You can use the difference of a consecutive numbering of all days and a consecutive numbering of all non-workingdays to use for the grouping.
For a consecutive group of non-workingdays, these differences will all have the same value, and because of the gaps (workingsdays) between the groups, the next group will have a different (higher) value.
For numbering all days, you can use DATEDIFF, for the numbering of non-workingdays you can use ROW_NUMBER. The query could look like this:
WITH
numbering (calendardate, grp_num) AS (
SELECT
calendardate,
DATEDIFF(day, 0, calendardate) - ROW_NUMBER() OVER (ORDER BY calendardate)
FROM YourTable WHERE ISNONWORKINGDAY = 1
)
SELECT
DATEADD(day, -1, MIN(calendardate)) AS StartDate,
DATEADD(day, +1, MAX(calendardate)) AS EndDate
FROM numbering GROUP BY grp_num;

calculate start date and end date from given quarter SQL

I want to get :
startdate and enddate from a given quarter from between dates
example :
range of dates : 2016-01-01 - 2016-12-31
1 (quarter) - will give me :
start date
2016-01-01
enddate
2016-03-31
2 (quarter) - will give me :
start date
2016-04-01
enddate
2016-06-30
and so on
I made it for only Quarter name and Year, modified it as your need
-- You may need to extend the range of the virtual tally table.
SELECT [QuarterName] = 'Q' + DATENAME(qq,DATEADD(QQ,n,startdate)) + ' ' + CAST(YEAR(DATEADD(QQ,n,startdate)) AS VARCHAR(4))
FROM (SELECT startdate = '01/Jan/2016', enddate = '31/DEC/2016') d
CROSS APPLY (
SELECT TOP(1+DATEDIFF(QQ,startdate,enddate)) n
FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) rc(n)
) x
Check below logic to get your answer.
DECLARE #Year DATE = convert(varchar(20),datepart(YEAR,getdate()))+'-01'+'-01'
DECLARE #Quarter INT = 4
SELECT DATEADD(QUARTER, #Quarter - 1, #Year) ,
DATEADD(DAY, -1, DATEADD(QUARTER, #Quarter, #Year))
SELECT DATEADD(QUARTER, d.q, DATEADD(YEAR, DATEDIFF(YEAR, 0,GETDATE()), 0))
AS FromDate,
DATEADD(QUARTER, d.q + 1, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), -1))
AS ToDate
FROM (
SELECT 0 UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3
) AS d(q)

Displaying start date of week in SQL

I have a SQL query that to return the number of items per week. I have a query that returns so far this:
Number of Items | Week Number
-------------------------------
100 | 18
80 | 19
120 | 20
And would like to return the following:
Number of Items | Week Beginning
-------------------------------
100 | 1st May 2017
80 | 8th May 2017
120 | 15th May 2017
What I have so far is:
SELECT COUNT(*) AS 'Number of Items', DATEPART(WEEK, Date) FROM table
where DATEPART(Year, Date) = '2017' and DATEPART(MONTH, Date) = 5
group by DATEPART(WEEK, Date)
You are talking about the 1st day of the current week:
example: select FORMAT(dateadd(ww,datediff(ww,0,getdate()),0),'dd MMM yyyy')--if you are using SQL 2012+
answer:
SELECT COUNT(*) AS 'Number of Items', FORMAT(dateadd(ww,datediff(ww,0,date_column),0),'dd MMM yyyy')
FROM table
where DATEPART(Year, Date) = '2017' and DATEPART(MONTH, Date) = 5
group by DATEPART(WEEK, Date)
As you need Monday to be the first day of the week
select DATEPART(WEEK, MyDate),DATEADD(DAY,1,(DATEADD(DAY, 1-DATEPART(WEEKDAY, MyDate), MyDate)))
from (
select '5/3/2017' MyDate
union all select '5/10/2017'
union all select '5/14/2017')A
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, Date) /7*7, 0) AS StartDateOfWeek
check this if it solves
DECLARE #WeekNum INT
, #YearNum char(4);
SELECT #WeekNum = 20
, #YearNum = 2017
-- once you have the #WeekNum and #YearNum set, the following calculates the date range.
SELECT DATEADD(wk, DATEDIFF(wk, 6, '1/1/' + #YearNum) + (#WeekNum-1), 6) AS StartOfWeek;
SELECT DATEADD(wk, DATEDIFF(wk, 5, '1/1/' + #YearNum) + (#WeekNum-1), 5) AS EndOfWeek;
thanks to http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=185440