Solved

Doing subtraction on dates

Posted on 2004-08-20
980 Views
I need to determine the average age for a set of data. I have the create date for each record and need to subtract that to get the age of each row. Then I also need to sum that up so that I have the total and can get the average. Is there a way to do this using SQL?

Thanks,
John
0
Question by:Pawlikj
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 19

Accepted Solution

Dexstar earned 250 total points
ID: 11854676
Pawlikj:

> I need to determine the average age for a set of data. I have the create date for
> each record and need to subtract that to get the age of each row. Then I also need
> to sum that up so that I have the total and can get the average. Is there a way to
> do this using SQL?

Yes, you can use the DATEDIFF function to get the age of the record.  Say you want to get the age in terms of "Days", you could do this:
SELECT *, DATEDIFF(days, CreateDate, GETDATE()) As DaysOld FROM YourTable

However, if you just want to find the average, then SQL can do all the work for you:
SELECT AVG( DATEDIFF(days, CreateDate, GETDATE()) ) As AverageDaysOld FROM YourTable

Hope That Helps,
Dex*
0

LVL 11

Expert Comment

ID: 11854679
You can use DATEDIFF function to find out the difference between two dates.

For syntax, check books online or

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_da-db_5vxi.asp

Similarly, If you want to add the dates you can use DATADD function. But, not sure what is the requirement, looks like, for your query, it is a normal addition (not date additioin) to find the average.
0

Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Suggested Courses
Course of the Month4 days, 12 hours left to enroll