reporting Wednesday to wednesday - sql

I am trying run a report based on a Wednesday to Wednesday reporting week.
I have found lots of examples that say the get correct date, such as:
DATEADD(DAY, -5, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0))
The problem is that these seem to only work for the current week. The example above gives 15/11/17 which is correct for today (24/11/2017) but incorrect on Sunday (26/11/2017) when it would get the 22/11/2017.
if I look at the report between 22-28/11/2017(Wed-Tue) I should see a report from 15-22/11/2017
Between the 29/11 & 5/12/2017 the report should be from 22-29/11/2017
any help is appreciated!

Try this method
SELECT
*,
CASE WHEN [wensday]>reportDate THEN DATEADD(WEEK,-2,[wensday]) ELSE DATEADD(WEEK,-1,[wensday]) END [from date],
CASE WHEN [wensday]>reportDate THEN DATEADD(WEEK,-1,[wensday]) ELSE [wensday] END [to date]
FROM
(
SELECT
reportDate,
-- monday of this week
--DATEADD(DAY,DATEDIFF(DAY,0,reportDate)/7*7,0) [monday],
-- wensday of this week
DATEADD(DAY,2,DATEADD(DAY,DATEDIFF(DAY,0,reportDate)/7*7,0)) [wensday]
FROM
(
SELECT CAST('20171115' AS date) reportDate
UNION ALL
SELECT CAST('20171121' AS date) reportDate
UNION ALL
SELECT CAST('20171122' AS date) reportDate
UNION ALL
SELECT CAST('20171123' AS date) reportDate
UNION ALL
SELECT CAST('20171124' AS date) reportDate
UNION ALL
SELECT CAST('20171129' AS date) reportDate
UNION ALL
SELECT CAST('20171205' AS date) reportDate
) test
) q
The inline algorithm
DECLARE #reportDate date=GETDATE()
DECLARE #Wensday date=DATEADD(DAY,2,DATEADD(DAY,DATEDIFF(DAY,0,#reportDate)/7*7,0))
DECLARE #FromDate date=CASE WHEN #Wensday>#reportDate THEN DATEADD(WEEK,-2,#Wensday) ELSE DATEADD(WEEK,-1,#Wensday) END
DECLARE #ToDate date=DATEADD(WEEK,1,#FromDate)
SELECT #reportDate,#Wensday,#FromDate,#ToDate

You can use DATEFIRST to assign days 1-7 to Wed - Tue
Whatever date you put in here, it will return the first prior Wednesday
The following Tuesday is just 6 days after that.
-- Wednesday will be 1 when we use datepart dw
SET DATEFIRST 3;
DECLARE #ReportDate DATE
SET #ReportDate = '2017-11-26'
SELECT
DATEADD( d,
-(DATEPART(dw,#ReportDate)-1),
#ReportDate
)

Try this...
DECLARE #fDt as date,#fDtR as date
set #fDt = '11/15/2017'
SET DATEFIRST 3
SELECT #fDtR = DATEADD(d,-6-(DATEPART(dw,#fDt)),#fDt)
print #fDtR

you can try this
select * from youtablename where yourdatefield <=
dateadd(dd,datediff(dd,0,getdate())/7 * 7 + 2,0)) and yourdatefield >
dateadd(dd,datediff(dd,0,getdate())/7 * 7 + 2,-7))
From this you will get last wednesday
select
dateadd(dd,datediff(dd,0,getdate())/7 * 7 + 2,0))
and from this you will get last to last wednesday
select dateadd(dd,datediff(dd,0,getdate())/7 * 7 + 2,-7))
so that you can find Wednesday to Wednesday data.

Related

How to get max Saturday dates in a column of each month, without hardcoding

How to get max Saturday dates in a column of each month in SQL Server. Can someone please help me.
Now I need only the dates which has last Saturday of month.
For example,
The table has
07-08-2021 - Saturday
14-08-2021 - Saturday
21-08-2021 - Saturday
28-08-2021 - Saturday
04-09-2021 - Saturday
11-09-2021 - Saturday
18-09-2021 - Saturday
25-09-2021 - Saturday
Suppose we are in August month, I need to select last Saturday of that month( ONLY 28-08-2021)
Suppose we are in September month, I need to select last Saturday of that month( ONLY 25-09-2021)
Output:
28-08-2021
25-09-2021
assuming you have a datefield in your table (I will refer to it here as such in the below query)
with week as (
select
date_trunc('week', datefield + interval '2 day') - interval '2 day' as week_date
-- ^this adjusts the week date_trunc to start on Saturday (it starts on Monday by default)
from sometable
)
select
extract(month from week_date) as month_num,
max(week_date) as last_saturday
from week
group by month_num
note: if you only have partial data for the current month, this query will need to be altered slightly, but you didn't give me a lot to go off of here
A CTE is defined to populate the day name of entire month and then the requirement is filtered.
;with GetDates As (
select CAST('01-01-2021' as date) as StartDate, datename(dw, '09-01-2021') as Day_Name
UNION ALL
select DATEADD(day,1, StartDate), datename(dw, DATEADD(day,1, StartDate))
from GetDates
where StartDate < '09-30-2021'
)
select max(StartDate)
from GetDates where Day_Name = 'Saturday'
group by month(StartDate)
OPTION (MAXRECURSION 500)
Here is a function to calculate the Nth Weekday - which can calculate from the beginning of the month or from the end of the month.
Alter Function dbo.fnGetNthWeekDay (
#theDate datetime
, #theWeekday int
, #theNthDay int
)
Returns Table
As
Return
/*
Adapted from a version published by Peter Larrson - with minor modifications for performance
and restructured to eliminate usage of a derived table.
Inputs:
#theDate any date in the month
#theWeekday the weekday to calculate: 1 = Monday
2 = Tuesday
3 = Wednesday
4 = Thursday
5 = Friday
6 = Saturday
7 = Sunday
#theNthDay the week count where positive is from beginning of the month
and negative is from end of month
Outputs:
#theDate the date entered
#theNthDate the Nth date of the month
*/
Select theDate = #theDate
, dt.nthDate
From (Values (dateadd(month, datediff(month, #theNthDay, #theDate), 0))) As mm(FirstOfMonth)
Cross Apply (Values (dateadd(day, 7 * #theNthDay - 7 * sign(#theNthDay + 1)
+ (#theWeekday + 6 - datediff(day, -53690, mm.FirstOfMonth) % 7) % 7, mm.FirstOfMonth))) As dt(nthDate)
Where #theWeekday Between 1 And 7
And datediff(month, dt.nthDate, #theDate) = 0
And #theNthDay In (-5, -4, -3, -2, -1, 1, 2, 3, 4, 5);
Go
You can then call it like this:
Select * From dbo.fnGetNthWeekDay('2021-08-15', 6, -1) nwd

Get weekends between two dates [duplicate]

This question already has answers here:
Get number of weekends between two dates in SQL
(5 answers)
Closed 7 years ago.
I have done the following so far:
declare #date int=7
declare #curDate date=getdate()
create table #temp(dat date,day1 varchar(max))
while #date>0
begin
insert into #temp values(#curDate,DATENAME(DW,#curDate))
set #curDate=DATEADD(Day,-1,#curDate)
if(DATENAME(DW,#curDate)<>'Saturday' and DATENAME(DW,#curDate)<>'Sunday')
begin
set #date=#date-1
end
End
select * from #temp
By this code i can easily find if there is a weekend between two date or not.
My question is:
Is there any other way to find if between two dates got a weekend or
not
e.g
date1 '03-25-2015' and date2 '03-30-2015' got a weekend or not??
Example/Expected Output:
table1
(
id bigint,
value1 varchar(50),
value2 decimal(18,2),
.
.
.
date1 date
)
let passdate1(firstdate(min)) and passdate2(last date (max)) is two
given date:
I want it like this:
select * from table1 where date1 between case
when (passdate1,passdate2) has weekend and it's no is 2 days
then passdate1 and dateadd(day,2,passdate2)
else
passdate1 and passdate2 end
Use recursive common table expressions to select all dates, then use DATEPART to determine if each date is a weekend
;WITH dates AS (
SELECT CONVERT( DATE, '2015-01-01' ) AS a
UNION ALL
SELECT DATEADD( DAY, 1, a )
FROM dates
WHERE DATEADD( DAY, 1, a ) < '2015-02-01'
)
SELECT a
FROM dates
WHERE DATEPART( dw, a ) IN ( 1, 7 )
Define "between". Does it have to be a full two-day weekend? Are the endpoints ever weekend days themselves? Are the endpoint dates ever the same?
I'm not quite sure how you're using the code above. You could possibly check that (select count(*) from #temp) < datediff(dd, #date1, #date2) but I don't get the impression you had that in mind.
Does this work for you? It would detect a full weekend when #date1 and #date2 are always weekdays.
datediff(dd, #date1, #date) > 5 or datepart(dw, #date2) < datepart(dw, #date1)
I'm assuming a weekend of Saturday and Sunday with day numbering that begins on Sunday.
Try this:
DECLARE #sd DATE = '20150326', #ed DATE = '20150329'
IF DATEDIFF(dd, #sd, #ed) >= 7 OR ( DATEPART(dw, #sd) = 7 AND DATEPART(dw, #ed) = 1 )
OR ( DATEDIFF(dd, #sd, #ed) >= 2 AND DATEPART(dw, #sd) > DATEPART(dw, #ed) )
PRINT 'YES'
ELSE
PRINT 'NO'
Try this solution which, essentially, computes difference in weeks between two dates and if those dates are equals it returns 0:
SELECT *,
DATEDIFF(WEEK, StartDate, EndDate) AS NumOfWeekends
FROM (VALUES
('2015-03-03', '2015-03-25'),
('2015-03-03', '2015-03-03'),
('2015-03-03', '2015-03-07'),
('2015-03-03', '2015-03-08'),
('2015-03-07', '2015-03-08'),
('2015-03-07', '2015-03-07'),
('2015-03-08', '2015-03-08'),
('2015-03-03', NULL)
) x(StartDate, EndDate);
/*
Output:
StartDate EndDate NumOfWeekends
---------- ---------- -------------
2015-03-03 2015-03-25 3
2015-03-03 2015-03-03 0
2015-03-03 2015-03-07 0
2015-03-03 2015-03-08 1
2015-03-07 2015-03-08 1
2015-03-07 2015-03-07 0
2015-03-08 2015-03-08 0
2015-03-03 NULL NULL
*/
Note: DATEDIFF(WEEK isn't dependent on ##DATEFIRST setting according to this.

tsql: How to retrieve the last date of each month between given date range

I have two date for example 08/08/2013 and 11/11/2013 and I need last date of each month starting from August to November in a table so that i can iterate over the table to pick those dates individually.
I know how to pick last date for any month but i am stucked with a date range.
kindly help, it will be highly appreciated.
Note : I am using Sql 2008 and date rang could be 1 month , 2 month or 6 month or a year or max too..
You can use CTE for getting all last days of the month within the defined range
Declare #Start datetime
Declare #End datetime
Select #Start = '20130808'
Select #End = '20131111'
;With CTE as
(
Select #Start as Date,Case When DatePart(mm,#Start)<>DatePart(mm,#Start+1) then 1 else 0 end as [Last]
UNION ALL
Select Date+1,Case When DatePart(mm,Date+1)<>DatePart(mm,Date+2) then 1 else 0 end from CTE
Where Date<#End
)
Select * from CTE
where [Last]=1 OPTION ( MAXRECURSION 0 )
DECLARE #tmpTable table (LastDates DATE);
DECLARE #startDate DATE = '01/01/2012'; --1 Jan 2012
DECLARE #endDate DATE = '05/31/2012'; --31 May 2012
DECLARE #tmpEndDate DATE;
SET #startDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#startDate)+1,1));
SET #tmpEndDate = DATEADD(DAY, 1, #endDate);
WHILE (#startDate <= #tmpEndDate)
BEGIN
INSERT INTO #tmpTable (LastDates) values (DATEADD(DAY, -1, #startDate));
SET #startDate = DATEADD(MONTH, 1, #startDate);
END
SELECT [LastDates] FROM #tmpTable;
Output:
Example: 1
#startDate DATE = '01/01/2012'; --1 Jan 2012
#endDate DATE = '05/31/2012'; --31 May 2012
LastDates
----------
2012-01-31
2012-02-29
2012-03-31
2012-04-30
2012-05-31
Example: 2
#startDate DATE = '11/01/2011'; --1 Nov 2011
#endDate DATE = '03/13/2012'; --13 Mar 2012
LastDates
----------
2011-11-30
2011-12-31
2012-01-31
2012-02-29
I've created a table variable, filled it with all days between #startDate and #endDate and searched for max date in the month.
declare #tmpTable table (dates date)
declare #startDate date = '08/08/2013'
declare #endDate date = '11/11/2013'
while #startDate <= #endDate
begin
insert into #tmpTable (dates) values (#startDate)
set #startDate = DATEADD(DAY, 1, #startDate)
end
select max(dates) as [Last day] from #tmpTable as o
group by datepart(YEAR, dates), datepart(MONTH, dates)
Results:
Last day
2013-08-31
2013-09-30
2013-10-31
2013-11-11
To also get last day of November this can be used before loop:
set #endDate = DATEADD(day, -1, DATEADD(month, DATEDIFF(month, 0, #endDate) + 1, 0))
Following script demonstrates the script to find last day of previous, current and next month.
----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth
If you want to find last day of month of any day specified use following script.
--Last Day of Any Month and Year
DECLARE #dtDate DATETIME
SET #dtDate = '8/18/2007'
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#dtDate)+1,0))
LastDay_AnyMonth
ResultSet:
LastDay_AnyMonth
Source - SQL Server Central.
You can use a recursive CTE to do this, note the MAXRECURSION OPTION prevents an infinite loop:
DECLARE #StartDate DATE = '2013-08-08'
DECLARE #EndDate DATE = '2013-11-11'
;WITH dateCTE
AS
(
SELECT CAST(DATEADD(M, 1,DATEADD(d, DAY(#StartDate) * -1, #StartDate)) AS DATE) EndOFMonth
UNION ALL
SELECT CAST(DATEADD(M, 2,DATEADD(d, DAY(EndOFMonth) * -1, EndOFMonth)) AS DATE)
FROM dateCTE
WHERE EndOFMonth < DATEADD(d, DAY(#EndDate) * -1, #EndDate)
)
SELECT *
FROM dateCTE
OPTION (MAXRECURSION 30);
This returns
EndOFMonth
----------
2013-08-31
2013-09-30
2013-10-31
try this
the last row(where) is optional for date filtering
declare #table table
(
thisdate date
)
insert into #table values ('12/01/2013'),('05/06/2013'),('04/29/2013'),('02/20/2013')
select *,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,thisdate)+1,0))
LastDay from #table
where thisdate between 'givendate' and 'givendate'
The Example Below is for all dates
thisdate lastday
2013-12-01 2013-12-31 23:59:59.000
2013-05-06 2013-05-31 23:59:59.000
2013-04-29 2013-04-30 23:59:59.000
2013-02-20 2013-02-28 23:59:59.000
The following CTE gives you the last day of every month from February 1900 until the middle of the 26th century (on my machine):
;with LastDaysOfMonths as (
select DATEADD(month,
ROW_NUMBER() OVER (ORDER BY so.object_id),
'19000131') as Dt
from sys.objects so,sys.objects so1
)
select * from LastDaysOfMonths
It should be easy enough to use it as part of a larger query or to filter it down to just the dates you want. You can adjust the range of years as needed by changing the constant 19000131. The only important thing to do is make sure that you use a month that has 31 days in it and always have the constant be for day 31.
No need to use a common table expression or anything like that - this simple query will do it:
SELECT DATEADD(d, -1, DATEADD(mm, DATEDIFF(m, 0, DATEADD(m, number, '2013-08-08')) + 1, 0)) AS EndOfMonth
FROM master.dbo.spt_values
WHERE 'P' = type
AND DATEADD(m, number, '2013-08-08') < '2013-11-11';
Although the question is about the last day which #bummi has already answered.
But here is the solution for the first date which might be helpful for someone.
Get the first dates of all the months in-between the #FromDate and #ToDate.
DECLARE #FromDate DATETIME = '2019-08-13'
DECLARE #ToDate DATETIME = '2019-11-25'
;WITH CTE
AS
(
SELECT DATEADD(DAY, -(DAY(#FromDate) - 1), #FromDate) AS FirstDateOfMonth
UNION ALL
SELECT DATEADD(MONTH, 1, FirstDateOfMonth)
FROM CTE
WHERE FirstDateOfMonth < DATEADD(DAY, -(DAY(#ToDate) - 1), #ToDate)
)
SELECT * FROM CTE
Here is the result
--Result
2019-08-01 00:00:00.000
2019-09-01 00:00:00.000
2019-10-01 00:00:00.000
2019-11-01 00:00:00.000

Get yesterdays date and if Monday get weekend range for SQL server

How do I get yesterdays date and if the current date is Monday I would need Sunday, Saturday and Friday. This is already asked here for ms access. I now need this for SQL server. How would I go about this?
Will create an inline view that will return the previous date in SQL It will return between 1 and 3 rows depending on the current date.
If current date is Monday Return:
Sundays date
Saturdays date
Fridays date
If current date is Tuesday then Return: Mondays date
If current date is Wednesday then Return: Tuesdays date
If current date is Thursday then Return: Wednesdays date
If current date is Friday then Return: Thursdays date
If current date is Saturday then Return: Fridays date
If current date is Sunday then Return: Saturdays date
I hope this helps explain what I am trying to do more clearly.
sample select query
--get previous date
select * from [Purchase Orders] where MyDate in (previous date(s))
Not entirely clear about the question though. But you can do something on the similar lines.
Using DATEPART and DATEADD
DECLARE #TodaysDate DATETIME
SET #TodaysDate = '2013-04-10'
SELECT CASE
WHEN DATEPART (DW, DATEADD (DD, -1, #TodaysDate )) IN (1, 6, 7)
THEN 'WeekEnd' ELSE 'WeekDay'
END D
Using the query you linked to, you can try the code below:
SELECT *
FROM [Purchase Order]
WHERE MyDate >= CASE
WHEN DATENAME(dw, CONVERT(CHAR(8), GETDATE() , 112)) LIKE 'Monday' THEN CONVERT(CHAR(8), DATEADD(dd, -3, GETDATE()), 112)
ELSE CONVERT(CHAR(8), DATEADD(dd, -1, GETDATE()), 112)
END
AND MyDate < CONVERT(CHAR(8),GETDATE(),112)
You can use the following table function:
CREATE FUNCTION dbo.ufnPreviousDay (#suppliedDate DATE)
RETURNS #PreviousDates TABLE (PreviousDate DATE)
AS
BEGIN
INSERT INTO #PreviousDates (
PreviousDate)
SELECT
PreviousDate = DATEADD(DAY, -1, #suppliedDate)
IF DATEPART(WEEKDAY, DATEADD(DAY, ##DATEFIRST - 1, #suppliedDate)) = 1 -- If Monday
BEGIN
INSERT INTO #PreviousDates (
PreviousDate)
SELECT
PreviousDate = DATEADD(DAY, -2, #suppliedDate)
UNION ALL
SELECT
PreviousDate = DATEADD(DAY, -3, #suppliedDate)
END
RETURN
END
You can use it like this:
SELECT
T.*
FROM
dbo.ufnPreviousDay('2018-03-19') AS T
/*
Result:
2018-03-18
2018-03-17
2018-03-16
*/
If you want today's previous dates:
SELECT
T.*
FROM
YourTable AS T
INNER JOIN dbo.ufnPreviousDay(GETDATE()) AS M ON T.MyDate = M.PreviousDate

How to get all the weekend dates of the current year in SQL?

I tried but could not get the right solution. I want an SQL query that lists all the weekend dates of the current year.
I tried this SQL query:
WITH hier(num, lvl) AS (
SELECT 0, 1
UNION ALL
SELECT 100, 1
UNION ALL
SELECT num + 1, lvl + 1
FROM hier
WHERE lvl < 100
)
SELECT lvl [Week],
convert(date,DATEADD(dw, -DATEPART(dw, DATEADD(wk,DATEDIFF(wk,0,'12/31/'+convert(nvarchar,YEAR(getdate()))), 0)+6 ),
DATEADD(wk, DATEDIFF(wk,0,'12/31/'+convert(nvarchar,YEAR(getdate()))), 0)+6 ) - num * 7,101) [End Date]
FROM hier a
where num < 52
ORDER BY [End Date] asc
Its output is like this:
Week End date
52 2012-01-14
51 2012-01-21
50 2012-01-28
49 2012-02-04
I want the dates to start from the beginning – so, the above is missing one weekend, which is 2012-07-01. Also, I want the week numbers to show as 1, 2, 3... instead of 52, 51....
Check out this blog post.
Your question is explained in detail.
DECLARE #Year AS INT,
#FirstDateOfYear DATETIME,
#LastDateOfYear DATETIME
-- You can change #year to any year you desire
SELECT #year = 2010
SELECT #FirstDateOfYear = DATEADD(yyyy, #Year - 1900, 0)
SELECT #LastDateOfYear = DATEADD(yyyy, #Year - 1900 + 1, 0)
-- Creating Query to Prepare Year Data
;WITH cte AS (
SELECT 1 AS DayID,
#FirstDateOfYear AS FromDate,
DATENAME(dw, #FirstDateOfYear) AS Dayname
UNION ALL
SELECT cte.DayID + 1 AS DayID,
DATEADD(d, 1 ,cte.FromDate),
DATENAME(dw, DATEADD(d, 1 ,cte.FromDate)) AS Dayname
FROM cte
WHERE DATEADD(d,1,cte.FromDate) < #LastDateOfYear
)
SELECT FromDate AS Date, Dayname
FROM CTE
WHERE DayName IN ('Saturday','Sunday') -- For Weekend
/*
WHERE DayName LIKE 'Sunday'
WHERE DayName NOT IN ('Saturday','Sunday') -- For Weekday
WHERE DayName LIKE 'Monday' -- For Monday
WHERE DayName LIKE 'Sunday' -- For Sunday
*/
OPTION (MaxRecursion 370)
Will this help
DECLARE #startDate DATETIME, #endDate DATETIME
SELECT #startDate = '2012-01-01', #endDate = '2012-12-31'
;WITH Calender AS (
SELECT #startDate AS dt
UNION ALL
SELECT dt + 1 FROM Calender
WHERE dt + 1 <= #endDate
)
SELECT
dt
,NameMonth = DATENAME(Month, dt)
,NameDay = DATENAME (Weekday,dt)
,WeekofYr = DATEPART(WEEK, dt) FROM Calender
WHERE DATENAME (Weekday,dt) IN ('Sunday')
Option(MaxRecursion 0)
Result(Partial)
dt NameMonth NameDay WeekofYr
2012-01-01 00:00:00.000 January Sunday 1
2012-01-08 00:00:00.000 January Sunday 2
...............................................
...............................................
2012-12-30 00:00:00.000 December Sunday 53
you can try this
DECLARE #FirstDateOfYear DATETIME
SET #FirstDateOfYear = ’2010-01-01′
SELECT DISTINCT DATEADD(d, number, #FirstDateOfYear),
CASE DATEPART(dw, DATEADD(d, number, #FirstDateOfYear))
WHEN 7 THEN ‘Saturday’
WHEN 1 THEN ‘Sunday’
ELSE ‘Work Day’
END
FROM master..spt_values
WHERE number BETWEEN 0 AND 364
AND (DATEPART(dw, DATEADD(d, number, #FirstDateOfYear)) = 1 OR DATEPART(dw, DATEADD(d, number, #FirstDateOfYear)) = 7)
ORDER BY DATEADD(d, number, #FirstDateOfYear)
Try to find the first Saturday by doing this:
Start on 2012-01-01
If it's not a Saturday, add a day
Goto 2
Then, into a temporary table, add that date and the following date (Sunday).
After that, loop the following:
Add 7 and 8 days to the last Saturday you found (you get the following Saturday and Sunday)
Check whether they are still in 2012
If they are, store them in temp table and goto 1
There may be more elegant ways, but that's my quick & dirty solution. As you didn't post any code of what you've tried, I'll leave the implementation up to you.
this also works
declare #dat datetime, #add int
set #dat = '20120101'
set #add = datepart(w,#dat)
set #add = 5 - #add -- friday
set #dat = dateadd(d,#add,#dat)
while #dat <= '20121231'
begin
print #dat
set #dat = dateadd(d,7,#dat)
end
;with AllDaysOfYear (Day) as (
select DATEADD(year,DATEDIFF(year,0,CURRENT_TIMESTAMP),0) --Jan 1st
union all
select DATEADD(day,1,Day) from AllDaysOfYear
where DATEPART(year,DATEADD(day,1,Day)) = DATEPART(year,CURRENT_TIMESTAMP)
)
select
ROW_NUMBER() OVER (ORDER BY Day) as WeekNo,
Day
from
AllDaysOfYear
where
DATEPART(weekday,Day) = DATEPART(weekday,'20120714')
option (maxrecursion 0)
First, generate a set of all of the days in the current year (AllDaysInYear). Then, select those whose weekday is a saturday. The value I've used ('20120714') isn't terribly important - it just has to be any saturday, from any year. I'm just using it to avoid needing to have particular DATEFIRST or language settings.
This query shows how to get the first day of this year and the first day of the next year in the first part. The first day of the next year is calculated once so as not to keep getting and comparing the year parts.
;WITH cte(TheDate,NextYear) AS
(
SELECT CAST(CONVERT(CHAR(4),GETDATE(),112)+'0101' AS DATETIME),
CAST(YEAR(GETDATE())*10000+10101 AS CHAR(8))
UNION ALL
SELECT DateAdd(d,1,TheDate),NextYear
FROM cte
WHERE DateAdd(d,1,TheDate)<NextYear
)
SELECT Week = DatePart(wk,TheDate),
TheDate
FROM cte
WHERE DateName(dw,TheDate) in ('Saturday')
ORDER BY TheDate
OPTION (MAXRECURSION 366)
with t as
(
select 1 b
union all
select 1 b
union all
select 1 b
union all
select 1 b
union all
select 1 b
union all
select 1 b
union all
select 1 b
union all
select 1 b
)
select * from
(
select
current_timestamp
-datepart(dy,current_timestamp)
+row_number() over (order by t.b) d
from t, t t1, t t2
) tmp
where datepart(yyyy,d)=datepart(yyyy,current_timestamp)
and
DATENAME(dw,d)='sunday'
DECLARE #Year AS INT
SELECT #Year = 2020
;WITH weekends AS (
SELECT DATEFROMPARTS(#Year, 1, 1) AS dt
UNION ALL
SELECT DATEADD(DAY, 1, dt)
FROM weekends
WHERE dt < DATEFROMPARTS(#Year, 12, 31)
)
SELECT dt, DATENAME(MONTH, dt), DATENAME(DW, dt)
FROM weekends
WHERE DATEPART(DW, dt) IN (1, 7)
OPTION(MaxRecursion 366)