SQL Server- selecting X amount of days between two dates - sql

I have a table with two Columns Date Created and Date Modified and I need to select all of the items where the date modified is more than 5 day past the created date.
I can compare the two columns fine but have not found out how to get it to know how many days between the two.
Thanks for the help.

You can use Datediff function from SQL and specify that you want "day" as datepart.
See msdn documentation about this function.
As JamesZ stated, "day" as datepart will only check if we are past 5 days without checking if 5 days really elapsed. So I added both in the select statement. Just use the one you want.
SELECT NbDays = DATEDIFF(DAY, DateCreated, DateModified),
*
FROM [YourTable]
WHERE DATEDIFF(DAY, DateCreated, DateModified) > 5
Or
SELECT NbDaysElapsed = DATEDIFF(MILLISECOND, StartDateTime, ENDDateTime) / 86400000,
*
FROM [YourTable]
WHERE (DATEDIFF(MILLISECOND, StartDateTime, ENDDateTime) / 86400000) > 5

Related

Two columns with dates (one any day of week, another one WEEK ENDING DATE (SATURDAY) BASED ON 1st column)

I have such a situation.
I need to have 2 columns 1) Is just pull data from a table (just as it is) r.[RCLDTE] (Day of week)
and 2 column) I need to basically look at the first column and make it Saturday of that week.
SELECT r.[RCLDTE] AS 'Day of Week'
,r.[RCLDTE] AS 'Week Ending Day (Saturday)'
Before what I was doing at similar projects I just used this code and added to WHERE statement.
WHERE CONVERT(DATE, CONVERT(CHAR(8), r.[RCLDTE] )) = cast(DATEADD(dd, DATEPART(DW,GETDATE())*-1, GETDATE()) as date)
This code was changing the dates column to Saturday.
However, here I have a different situation. I need 2 columns 1) as it is and 2) where dates will be Saturdays of the week from r.[RCLDTE] column , as a result from the way how I understand I cannot use WHERE statement because it will affect both columns.
Does someone know how I can leave 1st column as it is and 2nd a column of Saturday.
Please let me know.
Thanks.
To avoid issues when someone changes either DATEFIRST or LANGUAGE settings, you can use this. Also, given that you are storing dates in a numeric column for some reason (you really should provide feedback to whoever owns the system so they can fix it), we have to first try to convert those values to a date (they may not all be valid, which is one of the problems with using the wrong data type):
;WITH t AS
(
SELECT *, ProperDate = CASE WHEN ISDATE(CONVERT(char(8), RCLDTE)) = 1
THEN CONVERT(date, CONVERT(char(8), RCLDTE)) END
FROM dbo.tablename
)
SELECT [Language] = ##language, [Datefirst] = ##datefirst,
RCLDTE = CASE WHEN ProperDate IS NULL THEN RCLDTE END,
[Day of Week] = ProperDate,
[Saturday] = DATEADD
(
DAY,
6 - ((DATEPART(WEEKDAY, ProperDate) + ##DATEFIRST - 1) % 7),
ProperDate
)
FROM t;
Updated db<>fiddle that also demonstrates the handling of garbage data and a version of SQL Server so old that TRY_CONVERT() didn't exist yet (at least 12 years ago).
here is one way :
select
r.RCLDTE AS 'Day of Week'
, dateadd(day, 7 - datepart(weekday, r.RCLDTE) , r.RCLDTE)
from tablename r
db<>fiddle here

Calculate time from begin date in SQL

I'm trying to tally up the number of unique ID accounts that are active for more than a year as well as include how long each one is active. The problem with the code I have is it's not including accounts that are currently active (ones that don't have an end date). For example, if the begin date was May 01 2018 but has no end date since it's currently active, it should also be included in this query. Here's what I have so far..
SELECT UniqueID,
DATEDIFF(yy, Begin_Date,End_Date) as timeactive
FROM TABLE
WHERE DATEDIFF(yy, Begin_Date,End_Date) > 1
I want my output to look like...
Unique ID Time active
F000012 2.5
F000031 1.5
This is what ended up working:
SELECT UniqueID,
CAST(ROUND(DATEDIFF(day, Begin_Date, COALESCE(End_Date, getdate()))/365.0, 1, 0) AS NUMERIC (10,1)) as timeactive
FROM TABLE
WHERE DATEDIFF(day, Begin_Date, COALESCE (End_Date, getdate())) >= 365
If the EndDate is null then the output of the DateDiff function will be null, and any null compared to anything (even another null) is a result of null (usually then interpreted as false)
I suggest you use COALESCE to convert your end date to today if it is null:
SELECT
UniqueID,
DATEDIFF(yy, Begin_Date,COALESCE(End_Date, GetUtcDate()) as timeactive
FROM TABLE
WHERE DATEDIFF(yy, Begin_Date,COALESCE(End_Date, GetUtcDate()) > 1
You should bear in mind that the DATEDIFF function as used here, in SQLserver does NOT return the amount of time that has passed between the two dates. It returns the number of times the named interval has changed between the two dates
For example, DATEDIFF(year, 2000-01-01, 2000-12-31 23:59:59) will return 0 because these are both year 2000 even though they're just one second short of being a year apart. If you do DATEDIFF(year, 2000-12-31 23:59:59, 2001-01-01 00:00:01) even though these dates are only two seconds apart datediff will report them as 1 year apart because the year number has changed from 2000 to 2001.
DATEDIFF counts up by one every time the clock rolls past an interval change and in this case the interval is Year
To get your dates to report as 1.5 years etc you should consider to datediff by a smaller interval and divide, such as asking for the DAYS diff between two dates and then dividing by 365.25- the average number of days in a year. The smaller the interval you ask datediff for the more accurate the result will be but it'll never be 100%. If you're only after results to one decimal place of a year then days will be accurate enough
To get 1 decimal place, cast to a numeric with 1 DP:
SELECT
UniqueID,
CAST(DATEDIFF(day, Begin_Date,COALESCE(End_Date, GetUtcDate())/365.25 AS NUMERIC(5,1)) as timeactive
FROM TABLE
WHERE DATEDIFF(day, Begin_Date,COALESCE(End_Date, GetUtcDate()) >= 365
If you want time active as fractional years, then you need to use a smaller unit of time and divide. For instance:
SELECT UniqueID,
DATEDIFF(month, Begin_Date, COALESCE(End_Date, GETDATE())) / 12.0 as timeactive
FROM TABLE
WHERE Begin_Date < DATEADD(YEAR, -1, COALESCE(End_Date, GETDATE()))
Note the change in the WHERE clause. DATEDIFF() counts the number of year boundaries between dates. So the difference in years between 2019-01-01 and 2020-12-31 is the same as the difference between 2019-12-31 and 2020-01-01 -- exactly 1.
Consider:
SELECT
UniqueID,
DATEDIFF(yy, Begin_Date, COALESCE(End_Date, getdate()) as timeactive
FROM TABLE
WHERE DATEDIFF(yy, Begin_Date, COALESCE(End_Date, getdate()) > 1
This works by using the current date as default value for empty End_Dates. So this allows records with empty end date if their start date is more than one year ago.

Tableau Query for using DateDiff and DateTrun at same time

I am new to tableau and i need to find all row set filter on basis of given time frame and then grouping the result of same minute.I can crack this problem in Sql as following
select count(x)
from table t
where datediff(30, min, date)
group by datepart(min, date)
How to fix it in tableau ?
I'm not really sure of what you want but this will give you the number of record per minute, for the records whose date is in the last 30 minutes:
select datepart(MI, date) , COUNT(*) as NumberOfRecordsInMinute
from table t
where date >= dateADD(MI, -30, getdate())
group by datepart(MI, date)
order by datepart(MI, date)
It isn't obvious what your SQL is trying to do here as the standard SQL datediff function works like this datediff(datepart,startdate,enddate) and returns the difference between two dates in the units specified.
If that is what you want, then the Tableau function datediff does much the same job and datediff('minute',start date,enddate) will return the number of minutes between two datetimes and it will be grouped already because the result is discrete.
You can then count the number of records matching each minute difference.

SQL Server : get average per week for the past 30 weeks

I'm trying to figure out how to get the average CHECK_AMOUNT per week for the past/last 30 weeks in SQL Server 2008.
I tried something like this (see below) but I I think that is for months and not for weeks.
SELECT TOP 30
AVG(CHECK_AMOUNT) AS W2
FROM
CHECKS
WHERE
NOT UNT='256'
GROUP BY
YEAR(DATE_GIVEN), MONTH(DATE_GIVEN)
Can anyone show me how I can make that possible please,
Thank you...
Just use a where clause comparing the dates:
select AVG(CHECK_AMOUNT)
from CHECKS
WHERE NOT UNT='256' and DATEDIFF(d, Date_Given, getdate()) <= 30*7
I'm sorry; I misread the question. You want the average per week. Your original query is quite close
select DATEDIFF(d, Date_Given, getdate())/7 as weeks_ago, AVG(CHECK_AMOUNT)
from CHECKS
WHERE NOT UNT='256' and DATEDIFF(d, Date_Given, getdate()) <= 30*7
group by DATEDIFF(d, Date_Given, getdate())/7
I'm leaving the where clause in for selecting -- rather than using top 30 -- in case there are weeks with no checks.
Can you try to add this to the group by clause ?
datepart(week, DATE_GIVEN)
Try to use Datepart
SELECT TOP 30 AVG(CHECK_AMOUNT) AS W2 FROM CHECKS WHERE NOT UNT='256' GROUP BY Datepart(week,DATE_GIVEN)
I have run reports that cross over years and the Week has messed me up.
I use
YEAR(GETDATE()) * 100 + DATEPART(Week,GETDATE()) as my YearWeek value
Otherwise, if your data crosses over years, you'll be combining last year's week with this year's week.

SQL Select data by this week

Hi how do I get the data by current week?
Select * from Transaction where transactionDate ....
In SQL Server based on week of year. Please see DATEPART for ##DATEFIRST etc. for example, this is all trades since Sunday in US/UK settigs:
WHERE DATEPART(week, transactionDate) = DATEPART(week, GETDATE())
Edit:
For Access, use this DatePart and use "ww" for the part of date you want.
In answer to the comment, "week" is not a variable; it's the bit of the date you want
So:
WHERE DatePart("ww", transactionDate) = DatePart("ww", GETDATE())
In Microsoft Access
Last n days:
SELECT *
FROM Transaction
WHERE transactionDate >=Date()-7
If you have indexes and this type of difference suits, it will be faster because it is sargable
This week by week difference:
SELECT *
FROM Transaction
WHERE DateDiff("w",[transactionDate],Date())=0
BTW It is considered bad practice to use *
DateDiff: http://office.microsoft.com/en-us/access/ha012288111033.aspx
Simple but portable:
SELECT *
FROM Transaction
WHERE transactionDate >= ?
AND transactionDate <= ?
Calculate the two parameters in your server-side code to whatever definition of 'week' you need.
In IBM DB2
SELECT *
FROM Transaction
WHERE transactionDate BETWEEN CURRENT TIMESTAMP - 7 days AND CURRENT TIMESTAMP;
In Access, if you want to run a query to find records that fall in the current week, use
SELECT *
FROM table
WHERE table.DateField Between (Date()-Weekday(Date())+1) And (Date()-Weekday(Date())+7);
That runs Sunday through Saturday. Use +2 and +6 instead if you want the workweek.
mySQL (standard date stamp)
SELECT *
FROM Transaction
WHERE WEEK(NOW())=WEEK(transactionDate);
mySQL (unix timestamp stamp)
SELECT *
FROM Transaction
WHERE WEEK(NOW())=WEEK(FROM_UNIXTIME(transactionDate));
Bit of a unoptimized query. Could be a more efficient way.
Note: This isn't a rolling 7 days. Just the current week of the year.
EDIT: Sorry I didn't see the ms-access tag. ignore all of this :|