Select rows with date field having values within this week - sql

I am trying to select all the rows from a table where a date field has values within the current week. I want the rows from the current week's Monday until the current day.
Example:
ID adate
---------------
1 11-11-2010
2 12-11-2010
3 13-11-2010
4 14-11-2010
5 15-11-2010
The rows I want in this case are:
ID adate
---------------
4 14-11-2010 //this week's Monday
5 15-11-2010 //till today

This will work on a week from Sunday to Saturday. You shall adapt it if you want weeks from Monday to Sunday:
select *
from myTable
where aDate between
cast('now' as date) - extract(weekday from cast('now' as date)) --prev sunday
and
cast('now' as date) - extract(weekday from cast('now' as date)) + 6 --next saturday
;

I wrote it in ms sql:
declare #today as datetime
declare #first_day_of_week datetime
set #today = convert(varchar, getDate(), 101)
set #first_day_of_week = dateadd(day, -(DATEPART(WEEKDAY, #today) - 1), #today)
select *
from [table]
where adate between #first_day_of_week and #today
Sunday is the beginning of the week.

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

Calculate number Hours from Date range excluding weekend dates in sql

I have a range of date i.e start date 19/05/2017 till end date 25/05/2017. I want to get the hours calculated in between them without including weekends i.e friday and saturday.
For example:
7 days have 7*24= 168 hrs
5 days excluding friday and Saturday will give 120hrs.
Any function that can be used in another query?
create function dbo.GetHoursWithoutWeekends (#date1 date, #date2 date)
returns int
as
begin
declare #hours int
set #hours = 24 * (DATEDIFF(day, #date1, #date2) + 1 - (
select
count(DATEADD(day, t.Rbr - 1, #date1)) as WeekEndCount
from (
select
ROW_NUMBER() over (order by sc1.name) as Rbr
from sys.syscolumns sc1
cross join sys.syscolumns sc2
) t
where DATEADD(day, t.Rbr - 1, #date1) between #date1 and #date2
and DATEPART(weekday, DATEADD(day, t.Rbr - 1, #date1)) in (5, 6)
));
return #hours;
end
GO
set datefirst 1
select dbo.GetHoursWithoutWeekends ('20170519', '20170525')

Select week day names for the time interval

I have time interval, and I want my query to output a table with one column Days which is going to have all days of week in that interval in the natural order so if the interval is bigger than a week (i.e. between '2014-2-1' and '2014-2-21'), the result would be:
Day
----
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
If the interval starts, lets say on Friday and ends on the following Monday (i.e. between '2014-2-21' and '2014-2-24'), the output will be:
Day
----
Sunday
Monday
Friday
Saturday
I'd use the following approach:
generate a row for each day in your range (with ROW_NUMBER())
get the weekday for each generated row (using datename(weekday, ..) )
get the numeric weekday (using ##datefirst / datepart)
SQL:
DECLARE #StartDate DATE = '20140221'
, #EndDate DATE = '20140224'
SELECT
datename(weekday, v1.day) as weekday,
(((##datefirst-1) + datepart(weekday, v1.day)) % 7) as weekday_num,
v1.day FROM (
SELECT DATEADD(DAY, nbr - 1, #StartDate) AS day
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY c.object_id ) AS Nbr
FROM sys.columns c
) nbrs
WHERE nbr - 1 <= DATEDIFF(DAY, #StartDate, #EndDate)
) v1
order by 2
UPDATE
To correctly handle the case with more than 7 days, you can wrap it in another SELECT with DISTINCT:
DECLARE #StartDate DATE = '20140221'
, #EndDate DATE = '20140224'
SELECT DISTINCT weekday, weekday_num FROM (
SELECT
datename(weekday, v1.day) as weekday,
(((##datefirst-1) + datepart(weekday, v1.day)) % 7) as weekday_num,
v1.day FROM (
SELECT DATEADD(DAY, nbr - 1, #StartDate) AS day
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY c.object_id ) AS Nbr
FROM sys.columns c
) nbrs
WHERE nbr - 1 <= DATEDIFF(DAY, #StartDate, #EndDate)
) v1
) v2 order by 2
SQL Fiddle
You could use a combination of DatePart and DateName to do this. You can get your date like this:
select datename(dw,getdate()) --Friday
select datepart(dw,getdate()) --6
Just substitute getdate() (which would return today's date) with your field name. Then, you can display DateName but sort by DatePart.

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

Find the Friday that a particular date is "closest" to in T-Sql

I'm looking for an elegant simple way to determine the date of the Friday that is closest to a particular date. Any ideas?
The trick is to determine how many days away the closest Friday is from the offered date. To help, look at an entire week and the number of days away from the closest Friday:
Sunday -2
Monday -3
Tuesday 3
Wednesday 2
Thursday 1
Friday 0
Saturday -1
Now you need a formula to return these results. Because Sunday and Monday follow a different pattern from the other days of the week, two formulas are needed.
First, here is the one for Sunday and Monday. It adds 1 to the day of the week value then takes the negative to apply to the date add. For example, Monday has a default of 2 as the day of the week value. (2 + 1) * -1 = -3. -3 + Monday = Friday.
Tuesday - Saturday use similar arithmetic: The dates return the day of week values 3, 4, 5, 6, & 7. We need date add values of 3,2,1,0,-1 respectively. The formula to get this is DW * -1 + 6.
DECLARE #Date AS datetime
SET #Date = '3/1/2010'
SELECT
CASE
WHEN DATEPART(dw, #Date) <= 2
THEN DATEADD(d, -1 * (DATEPART(dw, #Date) + 1), #Date)
ELSE DATEADD(d, DATEPART(dw, #Date) * -1 + 6, #Date)
END AS NearestFriday
This returns a closest Friday in the future:
SELECT DATEADD(day, 6 - (DATEDIFF(day, '01/01/2010', #mydate) - 1) % 7, #mydate)
You have to slide the beginning of the week (using DATEFIRST) so that you get Tuesday becomes the middle of the week and then you just add the number of days to go to the closest Friday,.
SET NOCOUNT ON
SET DATEFIRST 3
Declare #DateValue DateTime
SET #DateValue = '1/1/2010'
While #DateValue < '2/1/2011'
BEGIN
PRINT DateAdd (Day, 3 - DatePart (dw, #DateValue), #DateValue)
SET #DateValue = #DateValue + 1
END
if you need to find the closest (past or future) Friday, try this:
DECLARE #StartDate datetime
,#EndDate datetime
,#BeforeDate datetime
SET #StartDate='2010-3-1'---<<<given date, Monday, closest should be '2010-2-26'
SET #EndDate=#StartDate+8
SET #BeforeDate=#StartDate-8
;with AllDates AS
(
SELECT #StartDate AS DateOf, 1 as TypeOf,DATENAME(weekday,#StartDate) AS WeekDayOf, ABS(DATEDIFF(day,#StartDate,#StartDate)) AS DifferenceOf
UNION ALL
SELECT DateOf+1 AS DateOf,2 AS TypeOf,DATENAME(weekday,DateOf+1 ) AS WeekDayOf, ABS(DATEDIFF(day,#StartDate,DateOf+1)) AS DifferenceOf
FROM AllDates
WHERE DateOf<#EndDate-1 AND TypeOf IN (1,2)
UNION ALL
SELECT DateOf-1 AS DateOf,3 AS TypeOf,DATENAME(weekday,DateOf-1 ) AS WeekDayOf, ABS(DATEDIFF(day,#StartDate,DateOf-1)) AS DifferenceOf
FROM AllDates
WHERE DateOf>#BeforeDate-1 AND TypeOf IN (1,3)
)
SELECT TOP 1 DateOf
FROM AllDates
WHERE WeekDayOf='Friday'
ORDER BY DifferenceOf
OUTPUT:
DateOf
-----------------------
2010-02-26 00:00:00.000
(1 row(s) affected)
SQL Server solution as a user-defined function. Will round not just to the nearest Friday, but to the nearest of any weekday (1-7) you specify:
CREATE FUNCTION RoundToNearestWeekday (
--Give this function a date, and the number of the weekday you want to round to the nearest of
#DateInput date, --Date you want to round
#ToWeekdayNumber tinyint --1 = round to nearest Sunday, 2 = round to nearest Monday, etc.
)
RETURNS date
AS
BEGIN
DECLARE #Offset tinyint, #LowNumber smallint, #HighNumber smallint, #NewDate date
SET #Offset = (#ToWeekdayNumber + 3)%7
SET #LowNumber = #Offset-3
SET #HighNumber = #Offset+4
SET #NewDate = dateadd(day,CASE WHEN datepart(weekday,#DateInput) <= #Offset THEN #LowNumber ELSE #HighNumber END - datepart(weekday,#DateInput),#DateInput)
RETURN #NewDate
END