SQL Server 2014 - How to get date range of 7 days ago plus 1 hour - sql

I need to pull up details from 1 hour past midnight, 7 days ago. But I'm not getting the results I need.
My code:
SELECT *
FROM Table
WHERE BusinessDay >= DateAdd(HOUR, 1, (DateAdd(DAY, -7, getdate()))) --#StartDate
AND BusinessDay <= DateAdd(HOUR, 1, getdate()) --#EndDate
When I give an actual time like below, I get the results I need:
WHERE BusinessDay >= '2018-04-04 00:01:000' --#StartDate
AND BusinessDay <= '2018-04-11 00:01:000' --#EndDate
I need to pass the dates in a parameters in SSRS. But clearly, the syntax is wrong in SSRS too.
I tried the below code but I get an error message:
WHERE BusinessDay >= DateAdd(HOUR, 1, (DateAdd(DAY, -7, CAST(getdate() as date)))) --#StartDate
AND BusinessDay <= DateAdd(HOUR, 1, CAST(getdate() as date)) --#EndDate
The error message: The datepart hour is not supported by date function dateadd for data type date.
So, I also tried the below code but got no results:
WHERE BusinessDay >= DateAdd(HOUR, 1, (DateAdd(DAY, -7, CAST(CAST(GETDATE() AS DATE) AS DATETIME)))) --#StartDate
AND BusinessDay <= DateAdd(HOUR, 1, CAST(CAST(GETDATE() AS DATE) AS DATETIME)) --#EndDate

Try this:
SELECT DATEADD(HH, 1, FORMAT(DATEADD(DD, -7, CAST(GETDATE() AS DATE)), N'yyyy-MM-dd HH:00:000'))
SQL Server 2014 introduced the FORMAT() function to make it easier to return/display data types in a formatting that you want without having to do a whole bunch of math with the formulas. Note: the format pattern is case-sensitive.
GETDATE() = '2018-04-11 18:20:00.000'
Formula Result: '2018-04-04 01:00:00.000'
For more information on the FORMAT() function, see here: https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql

With a little tweak to Gordon's answer to avoid an error produced by doing a CAST within the DATEADD function:
DECLARE #td DATETIME = CAST (GETDATE() AS DATE);
DECLARE #td1AM DATETIME = DATEADD(HOUR, 1, #td);
DECLARE #weekAgo1AM DATETIME = DATEADD(DAY, -7, #td1AM);
Then do your query with this:
SELECT *
FROM Table
WHERE BusinessDay >= #weekAgo1Am -- #StartDate
AND BusinessDay <= #td1AM -- #EndDate
For SSRS, via the answer linked in your comments, use TODAY():
DECLARE #td DATETIME = TODAY();
DECLARE #td1AM DATETIME = DATEADD(HOUR, 1, #td);
DECLARE #weekAgo1AM DATETIME = DATEADD(DAY, -7, #td1AM);
And the same query:
SELECT *
FROM Table
WHERE BusinessDay >= #weekAgo1Am -- #StartDate
AND BusinessDay <= #td1AM -- #EndDate

getdate() has a time component. So, remove it first:
WHERE BusinessDay >= DateAdd(HOUR, 1, (DateAdd(DAY, -7, cast(CAST(getdate() as date) as datetime)))) AND --#StartDate
BusinessDay <= DateAdd(HOUR, 1, cast(CAST(getdate() as date) as datetime)) --#EndDate

Related

Get data from last month in SQL Server

I checked Get the records of last month in SQL server and it did not work!
I try to get the records of last month based on my database table and column issue_date.
What's the SQL query to do this?
For clarification, today (27-April-18) I want to get all records from March-18.
I have the issue_date in the format that I convert to date but below code gives me all records from 01-March-2018 to and including today.
DATEPART(month, CONVERT (VARCHAR(11),DATEADD(day,wo_header.issue_date,`1971/12/31`),106)) = DATEPART(month, DATEADD(month, -1, getdate()))
To get firstDay and lastDay of previous month
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()))
SELECT #FirstDayOfLastMonth, #LastDayOfLastMonth
Your required Query
SELECT *
FROM TABLE
WHERE CAST(issue_date AS DATE) BETWEEN CONVERT(DATE, DATEADD(d, -(DAY(DATEADD(m, -1, GETDATE() - 2))), DATEADD(m, -1, GETDATE() - 1))) AND CONVERT(DATE, DATEADD(d, -(DAY(GETDATE())), GETDATE()))
Perhaps the easiest method is eomonth(). If there is no time component on issuedate:
where issuedate > eomonth(getdate(), -2) and
issuedate <= eomonth(getdate(), -1)
If there is a time component:
where issuedate >= dateadd(day, 1, cast(eomonth(getdate(), -2) as date)) and
issuedate < dateadd(day, 1, cast(eomonth(getdate(), -1) as date))
Without eomonth, I would do:
where issuedate < cast(dateadd(day, 1 - day(getdate()), getdate()) as date) and
issuedate >= dateadd(month, -1, cast(dateadd(day, 1 - day(getdate()), getdate()) as date))
The code I figured out is not pretty but it works. It first adds extra column with the month number to the SELECT portion of my code:
Month(CONVERT (VARCHAR(11),DATEADD(day,wo_header.closing_date,'1971/12/31'),106)) As Month
And than is used for WHERE statement:
Month(CONVERT (VARCHAR(11),DATEADD(day,wo_header.closing_date,'1971/12/31'),106)) = month(getdate())-1
So for anyone like me working in SQL report kind-of environment it should work.

Getdate() functionality returns partial day in select query

I have a query -
SELECT * FROM TABLE WHERE Date >= DATEADD (day, -7, -getdate()) AND Date <= getdate();
This would return all records for each day except day 7. If I ran this query on a Sunday at 17:00 it would only produce results going back to Monday 17:00. How could I include results from Monday 08:00.
Try it like this:
SELECT *
FROM SomeWhere
WHERE [Date] > DATEADD(HOUR,8,DATEADD(DAY, -7, CAST(CAST(GETDATE() AS DATE) AS DATETIME))) --7 days back, 8 o'clock
AND [Date] <= GETDATE(); --now
That's because you are comparing date+time, not only date.
If you want to include all days, you can trunc the time-portion from getdate(): you can accomplish that with a conversion to date:
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -convert(date, getdate())
AND Date <= convert(date, getdate());
If you want to start from 8 in the morning, the best is to add again 8 hours to getdate.
declare #t datetime = dateadd(HH, 8, convert(datetime, convert(date, getdate())))
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -#t) AND Date <= #t;
NOTE: with the conversion convert(date, getdate()) you get a datatype date and you cannot add hours directly to it; you must re-convert it to datetime.
Sounds like you want to remove the time. Correct? If so then do the following.
SELECT * FROM TABLE WHERE Date >= (DATEADD (day, -7, -getdate()) AND Date DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0))

Query for all records from 1:01 AM two days ago to 1 AM yesterday

I'm currently trying to write a query as part of an SSIS package, and part of the requirements is that the query will return all rows with a time stamp (currently in yyyy-mm-dd hh:mm:ss:mmm format) occuring from 1:01 AM 2 days ago to 1 AM 1 day ago. I can write this for dates, but I'm stuck on how to incorporate the hour range. Current query:
SELECT *
FROM
(SELECT dateadd(S, logintime, '1970-01-01') as "conversion"
,DATEPART(hh, dateadd(HOUR, logintime, '1970-01-01')) as "HourCol"
,DATEPART(hh, dateadd(MINUTE, logintime, '1970-01-01')) as "MinuteCol"
, * FROM my.logtable
WHERE row_date between dateadd(day, -3, getdate()) and DATEADD(day, -1, GETDATE())) as subselect
where conversion between --and from here I'm lost.
order by conversion
SELECT getdate() today,
CAST(getdate() as DATE) today_0000,
DATEADD(day, -1, CAST(getdate() as DATE)) yesterday0000,
DATEADD(day, -2, CAST(getdate() as DATE)) daybeforyesterday0000,
DATEADD(mi, 60, CAST(DATEADD(day, -1, CAST(getdate() as DATE)) as datetime)) yesterday0100,
DATEADD(mi, 61, CAST(DATEADD(day, -2, CAST(getdate() as DATE)) as datetime)) daybeforyesterday0101
Last two give you the range you are looking for. As long you compare with another datetime should work.

How do I find data from this day exactly one year ago?

Right now I have:
year(epe_curremploymentdate) = year(DATEADD(year, -1, SYSDATETIME()))
But that is giving me everything from last year. All I want is the data from today's date, one year ago.
It should be:
epe_curremploymentdate = DATEADD(year, -1, GETDATE())
Don't check for year in your where clause.
EDIT:
Simple: use
cast(epe_curremploymentdate AS DATE) = cast(DATEADD(year, -1,
GETDATE()) AS DATE)
That is, if you are using SQL Server 2008 and above.
This should get you to where you need to go:
Declare #StartDate datetime, #EndDate datetime
-- #StartDate is midnight on today's date, last year
set #StartDate = Convert(date, (DATEADD(year, -1, getdate())))
set #EndDate = DATEADD(Day, 1, #StartDate)
select *
from YourTable
where epe_curremploymentdate >= #StartDate
and epe_curremploymentdate < #EndDate
-- This where clause will get you everything that happened at any time
-- on today's date last year.
Date today:
select getdate()
date one year ago:
select dateadd(year, -1, getdate())
Date one year and one day ago:
select dateadd(d, -1 , dateadd(year, -1, getdate()))
UPDATE:
select *
from
epe_curremploymentdate = dateadd(year, -1, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))
This will give you a list of all employees who started working exactly from a year ago.
Hope this helps!!!
If you have other fields that show as datetime with the time part as 00:00:00.000, to do joins you can use the below
dateadd(yy,-1,datediff(d,0,getdate()))
epe_curremploymentdate = DATEADD(year, -1, GETDATE())

How do I compare against the current week using SQL Server?

How do I compare an SQL Server date column against the current week?
For instance:
WHERE [Order].SubmittedDate = *THIS WEEK*
You could convert your date to a week number and compare this to the week number from the current date. Likewise, you'll need to compare the year as well, so that you don't get last year's weeks.
WHERE DATEPART(wk, [Order].SubmittedDate) = DATEPART(wk, GETDATE())
AND DATEPART(yy, [Order].SubmittedDate) = DATEPART(yy, GETDATE())
Assuming you are meaning always "this week" and there are no records with Submitted dates in the future, which I imagine could be the case you can do:
WHERE [Order].SubmittedDate >= DATEADD(dd, -(DATEPART(dw, GETDATE()) -1), GETDATE())
If dates do go into the future, the full restriction to this week is:
WHERE [Order].SubmittedDate >= DATEADD(dd, -(DATEPART(dw, GETDATE()) -1), GETDATE())
AND [Order].SubmittedDate < CAST(CONVERT(VARCHAR(10), DATEADD(dd, (8 - DATEPART(dw, GETDATE())), GETDATE()), 120) AS DATETIME)
I'd strongly recommend using a clause based on a start and end date like this, as it will allow efficient index use so should perform better.
Try this:
WHERE [Order].SubmittedDate BETWEEN
DATEADD(d, - DATEPART(dw, GETDATE()) + 1, GETDATE()) AND
DATEADD(d, 7 - DATEPART(dw, GETDATE()) , GETDATE())
Maybe this can run faster, as doesn't needs to be evaluated everytime:
DECLARE #StartDate DATETIME,
#EndDate DATETIME
SELECT #StartDate = DATEADD(d, - DATEPART(dw, GETDATE()) + 1, GETDATE()),
#EndDate = DATEADD(d, 8 - DATEPART(dw, GETDATE()) , GETDATE())
-- // Strip time part, so week starts on Sunday 00:00
SELECT #StartDate = CAST(FLOOR(CAST(#StartDate AS FLOAT)) AS DATETIME),
#EndDate = CAST(FLOOR(CAST(#EndDate AS FLOAT)) AS DATETIME)
...
WHERE [Order].SubmittedDate >= #StartDate AND [Order].SubmittedDate < #EndDate