SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 looping through records with and without cursor
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

shantheguy
Starting Member

India
13 Posts

Posted - 04/20/2012 :  11:10:56  Show Profile  Reply with Quote
Hi all,

I have a requirement in sql server and it is as follows:

col1 col2 col3
10 120 2012-10-11
10 130 2012-12-11
10 140 2012-12-18

here my requirement is like i need to get the difference in dates record by record as below:

col1 col2 col3 col 4 days difference in col3 column
10 120 2012-10-11 0
10 130 2012-12-11 61
10 140 2012-12-18 7

How can i achieve this please help me out.

thanks in advance

sunitabeck
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 04/20/2012 :  11:43:27  Show Profile  Reply with Quote
You should be able to do a left join on to the table itself and calculate this. Since there is no sequential number, you would need to generate one - which is what the CTE in the query below does.
;WITH cte AS
(
	SELECT *,ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col3) AS RN
	FROM YourTable
)
SELECT
	a.col1, a.col3, a.col3,
	COALESCE(DATEDIFF(dd,b.col3,a.col3),0) AS differenceCol
FROM
	cte a
	LEFT JOIN cte b ON
		a.RN = b.RN+1
		AND a.col1 = b.col1
Go to Top of Page

shantheguy
Starting Member

India
13 Posts

Posted - 04/23/2012 :  01:01:00  Show Profile  Reply with Quote
Thanks alot...sunitabeck
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000