Solved

Doing subtraction on dates

Posted on 2004-08-20
2
976 Views
Last Modified: 2012-05-05
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
Comment
Question by:Pawlikj
2 Comments
 
LVL 19

Accepted Solution

by:
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

by:ram2098
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

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

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

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now