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 2008 Forums
 Transact-SQL (2008)
 Get two records at least year apart

Author  Topic 

oasis1
Starting Member

35 Posts

Posted - 2012-01-30 : 21:04:03
I need to get the 2 records for a patient that are at least a year old. We qualify a quitter to be some one who has not smoked for over a year. I need to pull the 1st and 4th record in this case and calculate the datediff and mark them as Quitter.

ID Appt Dates Status

22 01-01-2012 former smoker
22 10-21-2011 former smoker
22 05-10-2011 former smoker
22 11-23-2010 former smoker
22 08-20-2010 current smoker

mahalo, for your help....

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-01-31 : 00:09:26
[code]
SELECT CASE WHEN t.Status = t1.Status AND t.Status = 'former smoker' THEN 'Quitter' ELSE 'Non quitter' END
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Dates DESC) AS Rn,* FROM table) t
CROSS APPLY (SELECT TOP 1 Status
FROM table
WHERE ID = t.ID
AND Dates <= DATEADD(yy,-1,t.Dates)
ORDER BY Dates DESC
)t1
WHERE t.Rn=1
[/code]

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

Go to Top of Page
   

- Advertisement -