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
 General SQL Server Forums
 New to SQL Server Programming
 Comparing dates within a field? Is it possible?

Author  Topic 

gs
Starting Member

14 Posts

Posted - 2011-05-06 : 00:31:13
Hi,


I have a table with a f_number (integer) field and a date_transactions (datetime) field

f_number date_transactions
1 02/02/1999
2 04/06/1998
1 03/02/2000
1 04/04/2011
2 09/12/2005

Needed Output:

I want to create another column called previous_occurence where comparing within the date_transactions field and find out what was the previous date when the f_number field happened.
f_number date_transactions previous_occurence
1 02/02/1999 <null>
1 03/02/2000 02/02/1999
1 04/04/2011 03/02/2000
2 04/06/1998 <null>
2 09/12/2005 04/06/1998

Is there a way to compare dates within a date field and get the previous occurence of the date .

Thanks
Your help is much appreciated.
Any clue to work out this logic will be very helpful.

lionofdezert
Aged Yak Warrior

885 Posts

Posted - 2011-05-06 : 02:56:13
CREATE TABLE #Transactions (f_number INT, date_transactions DATETIME)

INSERT INTO #Transactions
SELECT 1, '02/02/1999' UNION ALL
SELECT 2, '04/06/1998' UNION ALL
SELECT 1, '03/02/2000' UNION ALL
SELECT 1, '04/04/2011' UNION ALL
SELECT 2, '09/12/2005'

SELECT f_number,
date_transactions,
( SELECT TOP ( 1 )
date_transactions
FROM #Transactions
WHERE f_number = OuterTable.f_number
AND date_transactions < OuterTable.date_transactions
ORDER BY f_number,date_transactions DESC
) AS previous_occurence
FROM #Transactions OuterTable
ORDER BY f_number,date_transactions

DROP TABLE #Transactions

--------------------------
http://connectsql.blogspot.com/
Go to Top of Page

gs
Starting Member

14 Posts

Posted - 2011-05-09 : 00:01:26
Thanks! that worked.
Go to Top of Page
   

- Advertisement -