Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
The scenario: A table of historical data showing state registration information. An example of the data looks like this:


IDStateStatusAsOfDate
2021AZA2001-05-21
2021AZT2004-12-31
2021AZA2010-01-01
2021CAA2001-05-21
2021WAA2001-05-21
2023AZA2005-01-04
2023MDA2003-07-01
2023WAA2002-05-21
2023WAT2007-05-21


ID = field rep identification number
State = state where a rep is licensed to work
Status = flag indicating Active or Terminated
AsOfDate = the date when the status changed

I need to figure out the query that will return the set of distinct states that are currently active for a given ID. That is to say, 2021 should return {AZ, CA, WA} (AZ was terminated and later reactivated) and 2023 should return {AZ, MD} (WA is still terminated.)

I would think this is a simple one, but I can't quite figure it out.
Posted

1 solution

The following query will work for you:

SQL
SELECT T.* FROM TestT T
JOIN (SELECT ID, State, MAX(AsOfDate) AsOfDate FROM TestT
GROUP BY ID, State) A ON T.Id = A.Id AND T.AsOfDate = A.AsOfDate
WHERE T.id = 2023
AND Status = 'A'


In this script TestT is the actual table which contain your data. Change the T.Id as per your need.

Hope this will help you.
 
Share this answer
 
Comments
Gregory Gadow 9-Feb-11 13:29pm    
Yup, that works! Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900