DATEADD 30 days from now is excluding one day - sql-server

I have a sql query...
When I run this query from today's date I will get records returned from 7/22/2016.
SELECT test_id, lat, long
FROM testDB.src.test_20
WHERE test_date >= DATEADD(day,-32, GETDATE()) and lat is not null and long is not null
When I change the DATEADD function to -31, I will get records from 7/23/2016.
SELECT test_id, lat, long
FROM testDB.src.test_20
WHERE test_date >= DATEADD(day,-31, GETDATE()) and lat is not null and long is not null
I might not be clearly understanding how the DATEADD function works. What I would think would happen when using -31, is that records from today to minus 31 days ago, including records from 7/22/2016 would be returned (since 31 days ago from today is 7/22/2016).
Why are records from 7/22/2016 not returned when using -31?
SQL Server Management Studio 2012

Consider just that expression on its own:
select DATEADD(day,-31, GETDATE())
2016-07-22 16:18:42.697
And then you look for rows with test_date greater than that date-time.
Perhaps you need to eliminate the time part and only consider days:
select DATEADD(day,-31, cast(GETDATE() as date))
2016-07-22
and date-times like 2016-07-22 10:15:00.420 will be found.

GETDATE() doesn't just include date but comes with the time stamp when you run.
For example
SELECT GETDATE()
returns
2016-08-22 10:21:36.867
So, when you add -31 in DATEADD(day,-31, GETDATE()), it compares your test_date to be greater than or equal to
2016-07-22 10:21:36.867
The more appropriate way to compare just dates is described below:
If you need to be specific about number of days
CONVERT(date, DATEADD(day,-31, GETDATE()))
which will result in just retrieving date part
2016-07-22
If you need to compare by calendar month
CONVERT(date, DATEADD(MONTH,-1, GETDATE()))
So, finally you should be writing your query as
SELECT
test_id,
lat,
long
FROM testDB.src.test_20
WHERE test_date >= CONVERT(date, DATEADD(DAY, -31, GETDATE()))
AND lat IS NOT NULL
AND long IS NOT NULL
For more information on GETDATE(), you can look at this MSDN article.

Related

Convert the date functions code to snowflake

This is sql server code, I have to convert this where condition to snowflake code, can I know how do we convert this into snowflake code and also I need explanation please.
where CONVERT(date, CONVERT(VARCHAR(8), 19000000+datecolumn)) >= cast(CONVERT(VARCHAR(25),DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) -1 , 0),120) as date)
and CONVERT(date, CONVERT(VARCHAR(8), 19000000+datecolumn)) <= cast(CONVERT(VARCHAR(25), DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1),120) as date)
so the left side is the same for both CONVERT(date, CONVERT(VARCHAR(8), 19000000+datecolumn))
so the outer most layer is a convertion to date which is snow falk can also be done via ::date and is side of that there is a conversion of a number to a 8 character string CONVERT(VARCHAR(8), 19000000+datecolumn) which is in a format that can be considered a date, and has the input as 19000000 + datecolumn so I would guess you date format is YYYYMMDD and datecolumn is YYMMDD since 1900. Which in snowflake would use the explicit form of TO_DATE
TO_DATE( ( 19000000 + datecolumn )::text, 'YYYYMMDD')
both the right hand sides are also comparing to dates, thus the outer CAST(... as date) which is the same as the ::text for I use above, see CAST
so the inner most part is DATEDIFF(MONTH, 0, GETDATE()) which is the number of months since beginning of time in your DB timeframe, and the current date in months, with 1 is subtracted from, and that many months are added since 0 in DB timeframe, thus DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) -1, 0) is the begin of the prior month. As today is December 22nd (if we pretend this year is year 0 in DB time) we are in month 12 which we minus 1 from thus add 11 months to 0 we get the date 2019-11-01, now 0 seems to be '1900-01-01' accord to the post, and I am going to guess the numeric value is whole days (as it's seems to be Microsoft's style), which would make the -1 start be the year '1899-12-31' and thus while we are finding one month month of time due to the date being a month prior, the date we are starting from is the end of the month, thus the second statement appears to be "end of the prior month" but I am not sure how SQL Server handles in the prior month was Feb, and thus if the end date is truncated to end of Feb, or if you end up 31 days after the start of the 1st of Feb.
Ether way that date is then turned to a text and then converted to date
It would again make more sense to just get the CURRENT_DATE(), truncate that to the month, and then step backward. And if you want the end of the prior month truncate and step back a day, or if you want 31 days, step forward that amount.
Thus
dateadd(month, -1, date_trunc('month', current_date())) as first_day_of_prior_month
dateadd(day, -1, date_trunc('month', current_date())) as last_day_of_prior_month
which is actually what the snowflake date-time help suggests

Get results for one day back in sql server

I am trying to get results from 1 day back, for example if i have a job that runs today at 1:00:00 am the 22/05/2018 i want it to get back the results for the 21/05/2018 00:00:00 am to 21/05/2018 23:59:59 pm.
i tried the follwing
select *
from table
where CreatedDateTime BETWEEN DATEADD(day, -1, GETDATE()) AND DATEADD(day, -0, GETDATE()) // it brings back everything from yesterday and today
example of how my created date time is stored in the db 2018-05-21 16:39:09.4830000
The bewteen operator filters the dates based on >= and <=
You need :
select *
from table
where CreatedDateTime >= DATEADD(day, -1, GETDATE()) AND
CreatedDateTime < GETDATE();
I suspect you would need cast(... as date) if so, the you can directly express this as
select *
from table
where cast(CreatedDateTime as date) = cast(DATEADD(day, -1, GETDATE()) as date);
Here is a good BLOG on filtering date range in query.
SELECT *
FROM table
WHERE CreatedDateTime BETWEEN GETDATE() -1 AND GETDATE()

SQL query in between dates does not work for "AM to PM"

SELECT GETDATE() StartDate
2018-03-28 10:24:44.747
SELECT GETDATE()+15 EndDate
2018-04-12 10:24:44.747
Column Login date is type DateTime
SELECT * FROM employee WHERE Logindate BETWEEN GETDATE() AND GETDATE()+15
I have around 300 records that matches the filter condition but I see only 60 records here for these dates
How can I check for Logindate in between "AM" till "PM"?
What you see as result of GETDATE() is the datetime format in 24 hours (so you don't see AM or PM).
If you want to check complete days, use the comparison with DATE format, or even better, truncate your GETDATE() result time component.
select
*
from
employee
where
Logindate >= CONVERT(DATE, GETDATE()) and
Logindate < CONVERT(DATE, DATEADD(DAY, 16, GETDATE())
Note that I'm adding 16 days but the filter is lower than (not including equal).

TSQL query for Week Comparison

I have a table that has a TASK_START_DATE and TASK_FINISH_DATE Columns of type datetime
I need help with a query that returns all Tasks when the Task: (date = just the date - I think I can do a conversion to the date from datetime on SQL 2008R2, it works fine)
- is within 2 weeks previous of the current date or two weeks after the current date.
Similarly I also need the records whose TaskEnd values are within 2 weeks previous or two weeks before
I've been trying things like which would get tasks where the start date is within the two previous weeks, but I have to do the same for TASK_FINISH_DATE and I think my and's and or's are all jumbled up, any help is appreciated.
Convert(Date, TASK_START_DATE) <= Convert(Date, DateAdd(ww, -2, GetDate()))
Short version:
How do I correctly write a query that combines all records with the TASK_START_DATE OR TASK_END_DATE within two weeks in the future or past, i.e.
Select Task_ID, TASK_NAME, TASK_START_DATE, TASK_END_DATE
where
???
You can add days to your date for comparision:
Select * from Table
Where column between getdate()-14 and getdate()+14
You don't need to use "Convert" function. "GetDate" function returns datetime value and your columns' types are datetime. You can add day number directly like this:
Select * from Table
Where (TASK_START_DATE between getdate() - 14 and getdate() + 14)
or (TASK_FINISH_DATE between getdate() - 14 and getdate() + 14)
You can declare variables or have the comparison dates right in the where clause. I use GETDATE() to get the date/time for right now as it returns a DATETIME object. Then I use DATEADD to adjust it for days, months, years, etc, and then you have to convert it to a DATE before sticking it in a variable of type DATE. Note in the DATEADD method I pass in the adjustment type (D = days), then adjust it + or - 14 days.
Alternatively you could just use 14 days ago to the minute if you don't do the DATE conversions...you'd have to remove the converts from the variable declarations as well as the where clause. Depends on the results you want though.
DECLARE #twoWeeksAgo DATE = CONVERT(DATE, DATEADD(D, -14, GETDATE()));
DECLARE #twoWeeksAhead DATE = CONVERT(DATE, DATEADD(D, 14, GETDATE()));
SELECT
Task_ID,
TASK_NAME,
TASK_START_DATE,
TASK_END_DATE
FROM
TABLE
WHERE
CONVERT(DATE, TASK_START_DATE) BETWEEN #twoWeeksAgo AND #twoWeeksAhead
OR CONVERT(DATE, TASK_END_DATE) BETWEEN #twoWeeksAgo AND #twoWeeksAhead
Also note that the BETWEEN operator in the WHERE clause is inclusive, meaning it will include records where the TASK_START_DATE is equal to the dates held by the variables. If you wanted to exclude records with the same value as #twoWeeksAhead, for example, you would have to use something like
WHERE
(CONVERT(DATE, TASK_START_DATE) >= #twoWeeksAgo
AND CONVERT(DATE, TASK_START_DATE) < #twoWeeksAhead)
OR (CONVERT(DATE, TASK_END_DATE) >= #twoWeeksAgo
AND CONVERT(DATE, TASK_END_DATE) < #twoWeeksAhead)

SQL QUERY ( SQL SERVER) Date & Time Difference

I have a SQL SERVER Table which has only one field "StartDate" the records are as follows
**
2011-07-28 19:30:00.000
2011-07-29 21:50:00.000
2011-07-25 09:20:00.000
**
What i want to do is :
SHOW RECORDS if its CURRENT DATE ( todays date ) and the time difference between current time the StartDate is not less then 5 minutes, i have written the following code but it doesnt show me the time difference ?
SELECT * FROM table WHERE DATEDIFF(day, StartDate, GETDATE()) <= 0
SELECT StartDate
FROM table
WHERE YEAR(StartDate)=YEAR(GETDATE())
AND MONTH(StartDate)=MONTH(GETDATE())
AND DAY(StartDate)=DAY(GETDATE())
AND (DATEDIFF(minute, StartDate, GETDATE()) >= 5
OR
DATEDIFF(minute, StartDate, GETDATE()) <= 5)
How about:
SELECT StartDate
,GETDATE()
,DATEDIFF(day, StartDate, GETDATE())
,DATEDIFF(minute, StartDate, GETDATE())
,*
FROM table
WHERE DATEDIFF(day, StartDate, GETDATE()) <= 0
AND DATEDIFF(minute, StartDate, GETDATE()) >= 5
There are two ways to do it one being DateDiff the other is DATEADD. Judging by the way I read your question DateAdd should do it. Here is an example;
SELECT *
FROM [dbo].[TABLE]
WHERE [LAST_UPDATE] > DATEADD(minute,-5,GetDate())
Using BETWEEN is probably a little more optimal than two AND statements (maybe not). Try not to do a calculation on each row if you don't have to. Doing DATEADD only on the current date will only be calculated once.
SELECT
whatever
FROM
table
WHERE
StartDate
BETWEEN FLOOR( CAST( GETDATE() AS FLOAT ) )
AND DATEADD(minute, -5, GETDATE())
I interpret the question as looking for rows where the date is today (between the start of today) but not within the last 5 minutes (and less than 5 minutes ago). That might not be what you were going for.
Hope that helps

Resources