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
 Help with query t0 find subsequent changes

Author  Topic 

SQLGeno
Starting Member

13 Posts

Posted - 2011-01-26 : 18:40:58
Hi guys\girls,
Any help with this appreciated. Consider the follow set

CaseId StatusId CreatedDate
-------------- ----------- -----------------------
13 1 2006-02-23 00:00:00.000
24 1 2006-09-13 00:00:00.000
24 2 2007-02-02 00:00:00.000
24 1 2007-06-13 11:27:03.000
24 1 2007-06-13 11:37:20.000
24 3 2007-06-28 11:31:58.763
24 3 2007-07-02 12:28:14.920
24 1 2007-08-14 00:00:00.000
24 3 2007-08-14 16:44:02.263
24 3 2007-08-14 16:44:02.263
24 3 2007-12-16 10:52:27.937
36 1 2004-03-03 02:00:00.000
36 2 2004-06-25 11:37:20.000
36 2 2005-01-17 15:38:46.000
36 2 2008-06-16 15:23:36.717
36 2 2008-06-16 15:23:36.717
36 3 2008-06-19 15:23:36.717
501 1 2011-01-20 08:38:03.927
501 1 2011-01-21 08:39:18.160
501 1 2011-01-22 08:43:38.393
501 3 2011-01-23 08:45:56.533
501 1 2011-01-25 08:45:56.533

For each CaseId, I need to look for a a given StatusId (in this case 3) and check to see if the status has subsequently been changed to a StatusId of 1.
i.e. I need find all the CaseIds where the Status has been set to 3 at some stage and then changed 1. What is the best way of going about this?

In the example shown CaseId 24 and 501 should be returned.

singularity
Posting Yak Master

153 Posts

Posted - 2011-01-26 : 19:01:50
[code]
select distinct CaseID
from yourtable a
where a.StatusID = 3 and
exists (select *
from yourtable b
where StatusID = 1 and
a.CaseID = b.CaseID and
a.CreatedDate < b.CreatedDate)
[/code]
Go to Top of Page

SQLGeno
Starting Member

13 Posts

Posted - 2011-01-26 : 23:10:33
Thanks Yak Master Singularity. Exactly what I was after.
Go to Top of Page
   

- Advertisement -