How to get the date from last Sunday to Saturday - sql

I will entries in my table which will have date with data like this:
Date Value
4-20-2014 45
4-21-2014 15
4-22-2014 35
...
4-30-2014 109
I will be executing my Stored Procedure every Sunday which means I would like to get the row with Date from previous Sunday until Yesterday (Saturday).
I have the following query which will get from Previous Sunday to Previous Saturday which I think is wrong so I modified it as the following:
INSERT INTO [database].[dbo].[table]
SELECT (WEEKENDING DATE) AS [Date], SUM([ORDERS]) AS Orders, SUM([B ORDERS]) AS bOrders, SUM([RESULT]) AS Results
FROM [database].[dbo].[origtable]
WHERE
[Date] >= "PREVIOUS SUNDAY DATE"
AND
[Date] <= "SATURDAY DATE (YESTERDAY)"
I would like to get some help with the following line:
[Date] >= "PREVIOUS SUNDAY DATE"
AND
[Date] <= "SATURDAY DATE (YESTERDAY)"
So if I run the SP on 5/4/2014, it will grab between Sunday (4/27/2014) to Saturday (5/3/2014)
Will this work:
INSERT INTO [Database].[dbo].[table]
SELECT
CONVERT(VARCHAR(10), GETDATE(), 101) AS [Date],
SUM([EMR ORDERS]) AS LastWeekEMROrders,
SUM([ACCESSIONED LAB ORDERS]) AS LastWeekAccLabOrders,
SUM([LAB_RESULT]) AS LastWeekLabResults
FROM [database].[dbo].[origtable]
WHERE
[Date] >= DATEADD(day, -((DATEPART(dw, GETDATE()) + ##DATEFIRST) % 7) - 6,
DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)) --PREVIOUS SUNDAY
AND
[Date] <= DATEADD(day, -(DATEPART(dw, GETDATE()) + ##DATEFIRST) % 7,
DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)) --PREVIOUS SATURDAY
If I have the following query and execute it on 5/4/2014:
set #startdate = DATEADD(wk, DATEDIFF(wk, 0, getdate()), -2) --for sunday
set #enddate = DATEADD(wk, -1, DATEADD(wk, DATEDIFF(wk, 0,getdate()), -1))-- for saturday
What will be the sunday's and saturday's date?

Try the following modified query:
EDIT:
The query has been further modified to not use DATEFROMPARTS.
INSERT INTO [Database].[dbo].[table]
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [Date], SUM([EMR ORDERS]) AS LastWeekEMROrders, SUM([ACCESSIONED LAB ORDERS]) AS LastWeekAccLabOrders, SUM([LAB_RESULT]) AS LastWeekLabResults
FROM [database].[dbo].[origtable]
WHERE
[Date] >= DATEADD(d, -8, DATEADD(dd, DATEDIFF(dd,0, current_timestamp), 0)) --PREVIOUS SUNDAY
AND
[Date] <= DATEADD(d, -1, DATEADD(dd, DATEDIFF(dd,0, current_timestamp), 0)) --PREVIOUS SATURDAY;
References:
Date and Time Data Types and Functions (Transact-SQL) on TechNet
Related SO question

Related

SQL fetch data for the present year until previous week friday

Am trying to fetch data in SQL until previous week Friday for the present year from the datetime field fetchDate
I tried something like this but it fetches until today
(year(fetchDate) = year(GETDATE()) and month(fetchDate) <= month(GETDATE()) and day(fetchDate) <= day(GETDATE()))
whereas
(year(fetchDate) = year(GETDATE()) and month(fetchDate) <= month(GETDATE()) and day(fetchDate) <= day(DATEADD(wk,DATEDIFF(wk,7,GETDATE()),4)))
brings me data only for the present month of the year until last week.
I believe what you need is the following:
WHERE YEAR(fetchDate) = YEAR(CURDATE())
AND fetchDate < DATE_SUB(NOW(), INTERVAL ((7 + WEEKDAY(DATE_SUB(NOW(), INTERVAL 1 WEEK)) - 4) % 7) DAY)
We get how many days ago last week's Friday was with:
((7 + WEEKDAY(DATE_SUB(NOW(), INTERVAL 1 WEEK)) - 4) % 7)
I would rather go for the following solution as it is sargable. Inside the WHERE predicate we are not wrapping the fetchdate into a function (e.g. YEAR(Fetchdate)), the query optimizer could use existing indexes and does not have to scan the whole table. Especially for BI workloads where this query is common, it is extremely important to optimize for that a lot of records are queried. It comes at the cost of little less readability
declare #tab table
(
fetchdate datetime
)
insert into #tab
values ('2019-01-01'),('2019-03-15'),('2018-12-31'),('2019-03-16')
SELECT
*,
case when datepart(weekday, getdate()) >5 then
DATEADD(DAY, +4, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0))
else DATEADD(DAY, -3, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0)) end as TestLastFriday,
DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) as TestFirstDayOfYear
FROM #tab
where
fetchdate <= case when datepart(weekday, getdate()) >5 then DATEADD(DAY, +4, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0))
else DATEADD(DAY, -3, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0)) end and
fetchdate >= DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)

Get last date of the previous month Transact-SQL

I am trying to fetch data for the previous full month, but the data from the last day is not fetching.
Output: Previous Month is April and this condition only retrieving data up to 29th April. Data for 30th April is missing.
Can please someone help me to correct this.
OLH.DateStamp > CONVERT(VARCHAR,DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0),101)
And
OLH.DateStamp < CONVERT(VARCHAR,DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1),101))
Thanks in advance
The simplest way to get data for the previous month is:
DATEDIFF(month, OLH.DateStamp, GETDATE()) = 1
However, that does not use indexes. So, a better method is:
OLH.DateStamp >= DATEADD(MONTH, -1, DATEADD(DAY, 1 - DAY(GETDATE()), CAST(GETDATE() as DATE))) AND
OLH.DateStamp < DATEADD(DAY, 1 - DAY(GETDATE()), CAST(GETDATE() as DATE))
The expression:
DATEADD(DAY, 1 - DAY(GETDATE), CAST(GETDATE() as DATE))
returns midnight on the first day of the current month.
You should try last day of Month Should be <= OLH.Datestamp
To get Desired Output you are Looking for:
--Use It In Where Clause
DECLARE #FirstDayOfLastMonth
DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, -1, GETDATE() -
2)) ), DATEADD(m, -1, GETDATE() - 1)))
,#LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE()) ), GETDATE()))
OLH.DateStamp >= CONVERT(VARCHAR, #FirstDayOfLastMonth , 101) AND
OLH.DateStamp <= CONVERT(VARCHAR, #LastDayOfLastMonth , 101)

First business day of the current month - SQL Server

How could I get the first business day of the current month?
Without create a function, only select.
something like that:
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(GETDATE())-1), GETDATE()), 101)
somebody knows please?
Thanks.
A Simple case statement could do it
SELECT CASE
WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, getdate()), 0)) = 'Saturday'
THEN dateadd(mm, DATEDIFF(MM, 0, getdate()), 0) + 2
WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, getdate()), 0)) = 'Sunday'
THEN dateadd(mm, DATEDIFF(MM, 0, getdate()), 0) + 1
ELSE dateadd(mm, DATEDIFF(MM, 0, getdate()), 0)
END
This will literally give you what you're asking for -- the first business day in a month if we define a business day as "any day that's not a Saturday or a Sunday". But this is is a very narrow definition of "business day" that is not appropriate when taking into account holidays and cultural differences, so it generalizes poorly. The typical solution for this problem is to create a table that actually holds the working days (which is generated somewhere just before he year, or calculated in advance if that's feasible), and simply look it up in that.
SELECT DATEADD(DAY,
CASE
(DATEPART(WEEKDAY, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) + ##DATEFIRST - 1) % 7
WHEN 6 THEN 2
WHEN 7 THEN 1
ELSE 0
END,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
)
This solution uses ##DATEFIRST to avoid any language issues -- using DATEPART(WEEKDAY, ...) on its own or DATENAME() only works if we assume a specific region.
If you have more flexibility in your SELECT statement, you might be able to use something like this:
;With Daterange As
(
Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0) As Date Union All
Select DateAdd(Day, 1, Date) As Date
From DateRange
Where Date < DateAdd(Day, 6, DateAdd(Month, DateDiff(Month, 0, GetDate()), 0))
)
Select Convert(Date, Min(Date)) FirstBusinessDay
From Daterange
Where DatePart(WeekDay, Date) Not In (7, 1)
Try this.
SELECT CASE
WHEN Datename(dw, Dateadd(dd, -Datepart(dd, Getdate()) + 1, Getdate())) = 'Saturday' THEN Dateadd(dd, -Datepart(dd, Getdate()) + 3, Getdate())
WHEN Datename(dw, Dateadd(dd, -Datepart(dd, Getdate()) + 1, Getdate())) = 'Sunday' THEN Dateadd(dd, -Datepart(dd, Getdate()) + 2, Getdate())
ELSE Dateadd(dd, -Datepart(dd, Getdate()) + 1, Getdate())
END
Explanation :
Find the first day of the month.
Dateadd(dd, -Datepart(dd, Getdate()) + 1, Getdate())
Then check the day of the previous date by using Datename function.
Datename(dw, Dateadd(dd, -Datepart(dd, Getdate()) + 1, Getdate()))
If the Datename is Saturday the add 2 days to the first day of the month . if it is sunday then add 1 day to the first day of the month else get the first day of the month

SQL - Get data based on months form a dateTime column

With SQL Server, I have a column with a launch date (dateTime). I want to report on everything that is being launched between all of last month (from viewing date) thru all of this month and next month.
So basically a full 3 month period.
What is the best way to write that?
Are you looking for something like this?
DECLARE
#StartDate DATETIME,
#EndDate DATETIME
SELECT
#StartDate = DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - 1, 0),
#EndDate = DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 2, 0)
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()), 0), -- beginning of this month
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - 1, 0), -- beginning of last month
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 1, 0) -- beginning of next month
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 2, 0) -- beginning of two months from now
SELECT
*
FROM
[Table]
WHERE
[LaunchDate] >= #StartDate
AND [LaunchDate] < #EndDate
This will give you all the results starting from the beginning of the previous month and before the beginning of two months from now (a full 3 month range)
Maybe something like SELECT /*what_you_want*/ from launches WHERE lauchDate BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - 1, '19000101') AND DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) + 2, '19000101')
SELECT Foo
FROM Bar
WHERE LaunchDate >= DATEADD(mm, -1, GETDATE())
AND LaunchDate <= DATEADD(mm, 1, GETDATE())

How to get the last month data and month to date data

Need help in writing the query to get the last month data as well as month to date data.
If today's date is Mar 23 2011, I need to retrieve the data from last month and the data till todays date(means Mar 23 2011).
If date is Apr 3 2011, data should consists of March month data and the data till Apr 3rd 2011.
Thanks,
Shahsra
Today including time info : getdate()
Today without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 0)
Tomorrow without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Beginning of current month : DATEADD(month, datediff(month, 0, getdate()), 0)
Beginning of last month : DATEADD(month, datediff(month, 0, getdate())-1, 0)
so most likely
WHERE dateColumn >= DATEADD(month, datediff(month, 0, getdate())-1, 0)
AND dateColumn < DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Step back one month, subtract the number of days to the current date, and add one day.
WHERE
DateField <= GetDate() AND
DateField >= DateAdd(
mm,
-1,
DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
)
To remove the time quickly, you can use this
Cast( Floor( Cast( GETDATE() AS FLOAT ) ) AS DATETIME )
So the second part would be (without time)
DateField >= Cast( Floor( Cast( (DateAdd(
mm,
-1,
DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
)) AS FLOAT ) ) AS DATETIME )
Select Column1, Column2 From Table1
Where DateColumn <= GetDate() AND
DateColumn >= DATEADD(dd, - (DAY(DATEADD(mm, 1, GetDate())) - 1), DATEADD(mm, - 1, GetDate()))
Edit: +1 to Russel Steen. I was posting mine before I knew he had posted.
Very helpful page
declare #d datetime = '2011-04-03';
declare #startDate datetime;
select #startDate =
CAST('01 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,-1,#d),113),8) AS datetime);
select #startDate;