Retrieve rows from a certain day but only in a certain hour - database

I have a query which returns all of the rows for three days ago:
SELECT * FROM table2
WHERE CONVERT(date, given_schedule)
= CONVERT(date, DATEADD(d, -3, GETDATE()))
But I want to know limit the rows to only the hour relative to the current time. So for example, it is currently after 9:00 PM then I only want to retrieve the rows that occurred three days ago and between 9:00 and 10:00 PM.

SELECT columns FROM dbo.table2
WHERE
CONVERT(DATE, given_schedule)
= CONVERT(DATE, DATEADD(DAY, -3, CURRENT_TIMESTAMP))
AND
DATEPART(HOUR, given_schedule)
= DATEPART(HOUR, CURRENT_TIMESTAMP);
To address #Habo's point, you could also do:
DECLARE #s SMALLDATETIME = CURRENT_TIMESTAMP;
SET #s = DATEADD(DAY, -3, DATEADD(MINUTE, -DATEPART(MINUTE, #s), #s));
SELECT columns FROM dbo.table2
WHERE given_schedule >= #s
AND given_schedule < DATEADD(HOUR, 1, #s);
This is, of course, most useful if there is actually an index with given_schedule as the leading column.

You could use the DATEDIFF function and pass in hour as the datepart argument.
SELECT * FROM table2 WHERE DATEDIFF(hour, GETDATE(), given_schedule,) BETWEEN 0 AND 1
See this for more info.

Related

Create a Select statement that determines a duration between 2 dates split out to each of the 2 dates

I have a table with records that contain the following columns:
Taskname, Start_Date, End_Date
I need to add a new column that shows the Duration between Start_Date and End_Date.
If a tasks overlaps multiple days I would need to create a split of duration for each of the dates
Example:
Start_Date = 4-6-2020 23:45:00 End date = 5-6-2020 00:00:16
Results 2 records showing the duration for each of the days:
4-6-2020 15
5-6-2020 16
Thank you for looking at my question
First you need a calendar table to return the days within the interval. You may already have one, if not I've made an example with a CTE as calendar.
After that we return an UNION, with the Start_Date and the minutes between Start_Date and End_Date if they are on the same day, or the minutes until next day. Adding the full days of the interval (the days within Start_Date + 1 and End_Date -1) with 24 * 60 minutes each. And finally adding the End_Date with the minutes from the previous day when it's a different day than Start_Date
create table MyLog (Start_Date datetime, End_Date datetime)
insert into MyLog (Start_Date, End_Date)
values ('2020-06-04 23:45', '2020-06-05 00:16')
declare #Start_Date date = (select min(Start_Date) from MyLog)
declare #End_Date date = (select max(End_Date) from MyLog)
;
with CTE as (
select #Start_Date as date
union all
select dateadd(day, 1, date) as date
from CTE
where date < #End_Date
)
select convert(date, Start_Date) as date,
case when convert(date, Start_Date) = convert(date, End_Date) then datediff(minute, Start_Date, End_Date)
else datediff(minute, Start_Date, dateadd(day, 1, convert(date, Start_Date)))
end as minutes
from MyLog
union all
select CTE.date,
24 * 60 as minutes
from MyLog
inner join CTE on CTE.date between dateadd(day, 1, convert(date, Start_Date)) and dateadd(day, -1, convert(date, End_Date))
union all
select convert(date, End_Date) as date,
datediff(minute, convert(date, End_Date), End_Date) as minutes
from MyLog
where convert(date, Start_Date) <> convert(date, End_Date)
See it online

How to get date from day name?

How can I get the date of specific day ? Like if I have Thursday or month number ?
If I give 12 for instance I want to get the date of 12th day of this month. Or if I give 'Sun' or 'Sat' is it possible to get the dates of these days ?
DATEFROMPARTS function can construct a date from day, month and year.
DATEPARTS does the opposite - gives you the day, month, year, hour, etc. of a date. Or you can use functions like YEAR, MONTH and DAY.
You can deconstruct the value returned by GETDATE function and construct whatever date you want. Here is for example how to get the date for 12th day of the current month:
select DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 12)
Converting 'Sun' or 'Sat' to date is a bit more difficult. First, they aren't quite deterministic. If today is Friday, "Sunday this week" means "next Sunday" in some parts of the world and "last Sunday" in others. You should implement your own logic based on the value returned by DATEPART(dw, GETDATE()) (which will give you the day of the week).
To find the weekday of the current month
DECLARE #daynumber INT = 12
SELECT datename(weekday, dateadd(d, #daynumber - 1, getdate()))
To find the dates of the current month of a given weekday
DECLARE #dayname char(3) = 'sat'
;WITH CTE as
(
SELECt TOP
(datediff(D, eomonth(getdate(), -1),eomonth(getdate())))
dateadd(d,row_number()over(ORDER BY 1/0),
eomonth(getdate(),-1))date
FROM
(values(1),(2),(3),(4),(5),(6))x(x),
(values(1),(2),(3),(4),(5),(6))y(x)
)
SELECT day(date) monthday, date
FROM CTE
WHERE left(datename(weekday, date),3) = #dayname
select sysdatetime(); --2018-12-13 16:29:56.0560574
---If I give 12 for instance I want to get the date of 12th day of this month.
declare #numDate int = 12;
select dateadd(m, datediff(m,0,getdate()),#numDate - 1 ); --2018-12-12 00:00:00.000
--Or if I give 'Sun' or 'Sat' is it possible to get the dates of these days ?
declare #text nvarchar(20) = 'Sunday';
declare #dateStart date = dateadd(month, datediff(month, 0, sysdatetime()), 0),
#days int =( select (DAY(dateadd(dd,-1,DATEADD(m,1,cast(2018 as varchar(4)) + '-' + cast(12 as varchar(2)) +'-01')))));
declare #dateEnd date = DATEADD(day,#days-1,#dateStart);
;WITH CTE (Dates,EndDate) AS
(
SELECT #dateStart AS Dates,#dateEnd AS EndDate
UNION ALL
SELECT DATEADD(day,1,Dates),EndDate
FROM CTE
WHERE DATEADD(day,1,Dates) <= EndDate
)
SELECT CTE.Dates, DATENAME(DW, CTE.Dates)
FROM CTE
where DATENAME(DW, CTE.Dates) = #text;
Result:
Dates,Day
2018/12/2,Sunday
2018/12/9,Sunday
2018/12/16,Sunday
2018/12/23,Sunday
2018/12/30,Sunday
-- Here is how to get week day name to week day number
DECLARE #T TABLE (Dow INT, NameOfDay VARCHAR(15), ShortName CHAR(3));
WITH Days AS
(
SELECT TOP 7
ROW_NUMBER() OVER(PARTITION BY object_id ORDER BY object_id) AS RowNo
FROM
sys.all_columns
)
INSERT INTO #T
SELECT
RowNo,
DATENAME(WEEKDAY, RowNo - 1),
LEFT(DATENAME(WEEKDAY, RowNo - 1), 3)
FROM
Days
SELECT
*
FROM
#T;
-- Here is how to get start of period
SELECT
DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0) AS StartOfDay,
DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0) AS StartOfWeek,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) AS StartOfMonth,
DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0) AS StartOfYear;
-- An example
WITH
StartPeriods AS
(
SELECT DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0) AS StartOfWeek
),
SelectedDay AS
(
SELECT
Dow - 1 AS Dow,
(SELECT StartOfWeek FROM StartPeriods) AS StartOfWeek
FROM
#T
WHERE
ShortName = 'Wed'
)
SELECT
DATEADD(DAY, Dow, StartOfWeek)
FROM
SelectedDay;

Find the First Wednesday after the last Tuesday of last financial month

One of my clients defines (for strange financial reasons) a financial month as a period of time that begins the Wednesday immediately after the last Tuesday of a Month (inclusive) and lasts until the last tuesday of the following month (inclusive).
I need to find the start of the last and the current financial month.
Some examples:
if today is September 23rd 2015 i need to get July 29th and August 26th because the current financial month goes from August 26th to September 29th.
If today is September 30th 2015 I need to get August 26th to September 30th.
I have different clients with different definitions and this means that some of them are using Wednesday and others are using Monday so i need this day to be a parameter, like Monday = 1 and Wednesday = 3. I call it FDOM, FirstDayOfMonth.
My work so far focused on using the formulas i found around with first and last days of current and last month, modified to take into account FDOM. I managed to get last Wednesday of Last Month but this sometimes is not correct because I am considering a day of the month that belongs to a solar month but also to the next financial month, like September 30th belongs to solar September but to Financial October, as financial October begins September 30th.
DECLARE #BASE AS DateTime = '19000101 00:00'
DECLARE #FDOM AS INT = 3 --Wednesday
DECLARE #Datevalue AS DATE = GETDATE()
SET DATEFIRST #FDOM
select DATEADD(D,1-(DATEPART(dw,DATEADD(D,-1,DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #Datevalue) , #BASE)))),DATEADD(D,-1,DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #Datevalue) , #BASE)))
This gives me the first wednesday after the last tuesday of last month and this would be correct from September 1st to September 29th (it gives August 26th) as "the beginning of the current financial month". But it would be wrong on September 30th as it should give September 30th and also wrong from August 26th till the end of August as it should give August 26th but instead gives July 29th.
I think this answers your requirements. Its quite long but hopefully, by breaking things out and naming things, I'm making it clear how we get to the final answer, and so if it's not quite right, it can be adapted:
declare #FDOM int
set #FDOM = 3 --Wednesday. 0 = Sunday, 6 = Saturday
declare #KnownDay datetime
set #KnownDay = DATEADD(day,#FDOM - 1,'20150301') --Offset from a "known good" Sunday to the day before FDOM
declare #EOLastDec datetime
set #EOLastDec = DATEADD(year,DATEDIFF(year,'20010101',GETDATE()),'20001231')
declare #Today datetime
set #Today = DATEADD(day,DATEDIFF(day,0,GETDATE()),0) --You can change this to test other key dates
;With Numbers(n) as (--If you have a numbers table, you can skip this CTE
select ROW_NUMBER() OVER (ORDER BY so1.object_id) - 1
from sys.objects so1 cross join sys.objects so2
), LastOfMonths as (
select DATEADD(month,n,#EOLastDec) as LOM
from Numbers
where n between 0 and 13
), LastImportant as (
select DATEADD(day,-n,LOM) as EOFMonth
from LastOfMonths cross join Numbers
where n between 0 and 6 and
DATEPART(weekday,DATEADD(day,-n,LOM)) = DATEPART(weekday,#KnownDay)
)
select DATEADD(day,1,li0.EOFMonth) as StartOfMonth,DATEADD(day,1,li1.EOFMonth) as EndOfMonth
from
LastImportant li1
cross join
LastImportant li2
left join
LastImportant li1_anti
on
li1.EOFMonth < li1_anti.EOFMonth and
li1_anti.EOFMonth <= #Today
left join
LastImportant li2_anti
on
li2.EOFMonth > li2_anti.EOFMonth and
li2_anti.EOFMonth >= #Today
inner join
LastImportant li0
on
li0.EOFMonth < li1.EOFMonth
left join
LastImportant li0_anti
on
li0_anti.EOFMonth < li1.EOFMonth and
li0.EOFMonth < li0_anti.EOFMonth
where
li1.EOFMonth <= #Today and
li2.EOFMonth >= #Today and
li1_anti.EOFMonth is null and
li2_anti.EOFMonth is null and
li0_anti.EOFMonth is null
Hopefully, the CTEs are reasonably explanatory. We generate a numbers table, and then we calculate the last day of each month, and from there, we step up to 6 days backwards to locate a day of the right type (i.e. a Tuesday, if #FDOM is 3)
I originally had a simpler final query using just li1 and li2 (and li1_anti and li2_anti), but realised that the query was just finding the current financial month - so I've added another couple of joins (using li0 and li0_anti) to find the start of the previous financial month.
Calculate the start date from previous month and the last day from current month and used a CTE to generate all dates between them. Later, get the MAX weekday from both months.
DECLARE #CurrentDate DATE = '2015-08-23'
DECLARE #StartDate DATE,
#EndDate DATE,
#MonthEnd INT = 3
-- Get the first day from previous month and last day from current month
SELECT #StartDate = DATEADD(MONTH , DATEDIFF(MONTH, 0, #CurrentDate)-1, 0),
#EndDate = DATEADD(SECOND,-1,
DATEADD(MONTH , DATEDIFF(MONTH, 0, #CurrentDate)+1,0))
;WITH Calendar AS
( -- Generate all dates between #StartDate and #EndDate
SELECT #StartDate [Date]
UNION ALL
SELECT DATEADD(D, +1, Calendar.[Date])
FROM Calendar
WHERE Calendar.[Date] < #EndDate
)
SELECT DATEADD(DAY, +1, MAX(StartDate.[Date])) StartDate,
DATEADD(DAY, +1, MAX(EndDate .[Date])) EndDate
FROM Calendar StartDate,
Calendar EndDate
WHERE -- Get the max weekday from previous month
DATEPART(MONTH , StartDate.[Date]) = DATEPART(MONTH, #StartDate) AND
DATEPART(WEEKDAY, StartDate.[Date]) = #MonthEnd AND
-- Get the max weekday from current month
DATEPART(MONTH , EndDate .[Date]) = DATEPART(MONTH, #EndDate) AND
DATEPART(WEEKDAY, EndDate .[Date]) = #MonthEnd
Try this. You can use EOMONTH function to get the end of month on Sql Server 2012 or above.
Click to see the fiddle demo.
DECLARE #date DATETIME = GETDATE()
DECLARE #LastMonthEnd DATETIME = DATEADD(day, -1, DATEADD(month, DATEDIFF(month, 0, #date), 0))
DECLARE #CurrentMonthEnd DATETIME = DATEADD(day, -1, DATEADD(month, DATEDIFF(month, 0, #date) + 1, 0))
SET DATEFIRST 1
;WITH CTE1 AS
(
SELECT 1 number, DATEPART(WEEKDAY, #LastMonthEnd) FirstDay,
DATEPART(WEEKDAY, #CurrentMonthEnd) LastDay
UNION ALL
SELECT 1+number, DATEPART(WEEKDAY, DATEADD(DAY, -number, #LastMonthEnd)),
DATEPART(WEEKDAY, DATEADD(DAY, -number, #CurrentMonthEnd))
FROM CTE1
WHERE number < 7
)
SELECT DATEADD(DAY, -(SELECT Number FROM CTE1 WHERE FirstDay = 3), #LastMonthEnd) StartDate,
DATEADD(DAY, -(SELECT Number FROM CTE1 WHERE LastDay = 3), #CurrentMonthEnd) EndDate
After a lot of effort I managed to find an expression that DOES NOT use CTE as i am not sure i can't use CTE in all the places i will have to employ this.
So basically first i understand with a CASE if the date i am considering is before or after the last Wednesday of the Month it belongs to. Then i return the last wednseday of two and of one month ago OR the last wednesday of one month ago and of this month.
This works also changing FDOM and i tested it for several months of this year. It seems to always work.
Probably the use of EOMonth would shorten it but i have to verify i can use it in my server.
I am sorry i just specified as a requirement that i can't use a CTE only in the comments but thank you for your help
DECLARE #datevalue AS Datetime = getdate()
DECLARE #BASE AS DateTime = '19000101 00:00'
DECLARE #FDOM AS INT = 3 --1 is for Monday
SET DATEFIRST #FDOM
SELECT CASE WHEN (#datevalue < DATEADD(D, 1-(DATEPART(dw,DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #datevalue) + 1, #BASE))),DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #datevalue) + 1, #BASE)))
THEN(DATEADD(D, 1-(DATEPART(dw,DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #datevalue) - 1, #BASE))),DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #datevalue) - 1, #BASE)))
ELSE(DATEADD(D, 1-(DATEPART(dw,DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #datevalue) - 0, #BASE))),DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #datevalue) - 0, #BASE)))
END AS [Start of Last Financial Month]
,CASE WHEN (#datevalue < DATEADD(D, 1-(DATEPART(dw,DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #datevalue) + 1, #BASE))),DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #datevalue) + 1, #BASE)))
THEN(DATEADD(D, 1-(DATEPART(dw,DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #datevalue) + 0, #BASE))),DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #datevalue) + 0, #BASE)))
ELSE(DATEADD(D, 1-(DATEPART(dw,DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #datevalue) + 1, #BASE))),DATEADD(MONTH, DATEDIFF(MONTH, #BASE, #datevalue) + 1, #BASE)))
END AS [Start of Current Financial Month]

Stored Procedure group by date set values for a missing date

In my stored procedure I return the total number of minutes grouped by the dates. The date ranges are one week from yesterday. The procedure is working fine. However, there's one issue I'm facing. Not always between the 7 days there will be any data for a particular day.
So for example, if I run my procedure today it returns this.
**Min Date**
47 2014-08-03
153 2014-08-04
45 2014-08-05
166 2014-08-06
This particular person doesn't have any data for the 31st of July,1st and second of August. So there will be no data returned from stored procedure.
What I want to do is return 0 for the days where there're no records in the database.
**Min Date**
0 2014-07-31
0 2014-08-01
0 2014-08-02
47 2014-08-03
153 2014-08-04
45 2014-08-05
166 2014-08-06
Here's the procedure:
ALTER PROCEDURE [dbo].[getAgentChartData]
(
#ABID BIGINT
)
AS
BEGIN
SET NOCOUNT ON;
--RETURNING 7 DAYS WORTH OF DATA FROM YESTERDAY
DECLARE #TODAY AS DATE =GETDATE(),#WEEK AS DATE
SET #WEEK = DATEADD (DD, -8, #TODAY)
SELECT SUM(MINUTES) AS TOTALMINUTES, CONVERT(DATE, STARTDATE) AS DATE FROM PoLines
WHERE ADDRESSBOOKID = #ABID AND STARTDATE BETWEEN #WEEK AND #TODAY
GROUP BY CONVERT(DATE, STARTDATE)
END
Any suggestions?
EDIT*
Added Hogan's suggestion. Still experiencing issue.
WITH Dates AS
(
SELECT DATEADD (DD, -7, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -6, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -5, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -4, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -3, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -2, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -1, GETDATE()) AS DAY
)
SELECT SUM(MINUTES) AS TOTALMINUTES, CONVERT(DATE, Dates.Day) AS DATE
FROM Dates
LEFT JOIN PoLines ON CONVERT(DATE, STARTDATE) = CONVERT(DATE, Dates.Day)
WHERE ADDRESSBOOKID = #ABID
GROUP BY CONVERT(DATE, Dates.Day)
In a small case like this I just make an inline table with a CTE. Like this:
WITH Dates AS
(
SELECT DATEADD (DD, -8, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -7, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -6, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -5, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -4, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -3, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -2, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -1, GETDATE()) AS DAY
)
SELECT SUM(ISNULL(MINUTES,0)) AS TOTALMINUTES, CONVERT(DATE, Dates.Day) AS DATE
FROM Dates
LEFT JOIN PoLines ON CONVERT(DATE, STARTDATE) = CONVERT(DATE, Dates.Day)
AND ADDRESSBOOKID = #ABID
GROUP BY CONVERT(DATE, Dates.Day)
Because you are left joining from the Dates table you will get all elements of the Dates table and whatever elements of the PoLines table exist. Then the group by will roll this up to 7 rows.
You can also setup a dates table in your DB to join from and use a where clause to limit the date range (this is a standard practice.)
Note, I don't have access to a DB right now so I did not test the SQL it might have a typo.

how to get data of current week only in SQL server?

I want records from table which stores the current date when a record is inserted with in current week only.
I have tried:
SELECT PId
,WorkDate
,Hours
,EmpId
FROM Acb
WHERE EmpId=#EmpId AND WorkDate BETWEEN DATEADD(DAY, -7, GETDATE()) AND GETDATE()
Do it like this:
SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT [...]
AND WorkDate >= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND WorkDate < dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
Explanation:
datepart(dw, getdate()) will return the number of the day in the current week, from 1 to 7, starting with whatever you specified using SET DATEFIRST.
dateadd(day, 1-datepart(dw, getdate()), getdate()) subtracts the necessary number of days to reach the beginning of the current week
CONVERT(date,getdate()) is used to remove the time portion of GETDATE(), because you want data beginning at midnight.
A better way would be
select datepart(ww, getdate()) as CurrentWeek
You can also use wk instead of ww.
Datepart Documentation
Its Working For Me.
Select * From Acb Where WorkDate BETWEEN DATEADD(DAY, -7, GETDATE()) AND DATEADD(DAY, 1, GETDATE())
You have to put this line After the AND Clause AND DATEADD(DAY, 1, GETDATE())
datepart(dw, getdate()) is the current day of the week, dateadd(day, 1-datepart(dw, getdate()), getdate()) should be the first day of the week, add 7 to it to get the last day of the week
You can use following query to extract current week:
select datepart(dw, getdate()) as CurrentWeek
SET DATEFIRST 1;
;With CTE
AS
(
SELECT
FORMAT(CreatedDate, 'MMMM-yyyy') as Months,
CASE
WHEN YEAR(DATEADD(DAY, 1-DATEPART(WEEKDAY, Min(CreatedDate)), Min(CreatedDate))) < YEAR(Min(CreatedDate))
THEN FORMAT(DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0 ,GETDATE())), 0) ,'MMM dd') + ' - ' + FORMAT(DATEADD(dd, 7-(DATEPART(dw, Min(CreatedDate))), Min(CreatedDate)) ,'MMM dd')
ELSE
FORMAT(DATEADD(DAY, 1-DATEPART(WEEKDAY, Min(CreatedDate)), Min(CreatedDate)) ,'MMM dd') + ' - ' + FORMAT(DATEADD(dd, 7-(DATEPART(dw, Min(CreatedDate))), Min(CreatedDate)) ,'MMM dd')
END DateRange,
Sum(ISNULL(Total,0)) AS Total,
sum(cast(Duration as int)) as Duration
FROM TL_VriandOPI_Vendorbilling where VendorId=#userID and CompanyId=#CompanyID
Group By DATEPART(wk, CreatedDate) ,FORMAT(CreatedDate, 'MMMM-yyyy')
)
SELECT Months,DateRange,Total,Duration,
case when DateRange=(select FORMAT(DATEADD(DAY, 1-DATEPART(WEEKDAY, Min(getdate())), Min(getdate())) ,'MMM dd') + ' - ' +
FORMAT(DATEADD(dd, 7-(DATEPART(dw, Min(getdate()))), Min(getdate())) ,'MMM dd'))
then 1 else 0 end as Thisweek
FROM CTE order by Months desc
Using DATEDIFF works as well, however a bit hacky since it doesn't care about datefirst:
set datefirst 1; -- set monday as first day of week
declare #Now datetime = '2020-09-28 11:00';
select *
into #Temp
from
(select 1 as Nbr, '2020-09-22 10:00' as Created
union
select 2 as Nbr, '2020-09-25 10:00' as Created
union
select 2 as Nbr, '2020-09-28 10:00' as Created) t
select * from #Temp where DATEDIFF(ww, dateadd(dd, -##datefirst, Created), dateadd(dd, -##datefirst, #Now)) = 0 -- returns 1 result
select * from #Temp where DATEDIFF(ww, dateadd(dd, -##datefirst, Created), dateadd(dd, -##datefirst, #Now)) = 1 -- returns 2 results
drop table #Temp

Resources