Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Subtracting Dates in same table in same column

Author  Topic 

futureSQLguru
Starting Member

1 Post

Posted - 2011-10-03 : 14:58:07
Good afternoon all,
This is my first post so if a similar question has already been posted and answered please forgive my redundency.

I have a table with the following columns
CL_ID DATE_REMOVED DATE_RETURNED NBR_OF_MOVES

5 1/4/2000 1/10/2001 1
5 4/9/2004 9/2/2005 2
5 1/4/2006 5/17/2007 3
5 7/23/2008 NULL 4

What I'm trying to do is create a SQL statement that will subtract the 'DATE_RETURNED' date from the next 'DATE_REMOVED' date. So essentially the results would look like the following:

CL_ID DATE REMOVED CALCULATION
5 1/4/2000 (4/9/2004 - 1/10/2001) =
5 4/9/2004 (1/4/2006 - 9/2/2005) =
5 1/4/2006 (7/23/2008 - 5/17/2007) =

I know how to subtract the dates, what I am having difficulty with is how to set up the query to do the actual subtraction if the table is set up this way. Any help would be much appreciated.

~future

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-10-03 : 15:16:47
[code]SELECT t.CL_ID,t.DATE_REMOVED,DATEDIFF(dd,t.DATE_RETURNED,t1.DATE_REMOVED)
FROM table t
OUTER APPLY (SELECT TOP 1 DATE_REMOVED
FROM table
WHERE CL_ID = t.CL_ID
AND DATE_REMOVED > t.DATE_RETURNED
ORDER BY DATE_REMOVED ASC)t1
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -