Help with SQL. Conditional selection of record

I have a set of records that have a taskID, taskState and taskDatetime, among other columns.    I want a set of records, one for each taskID, for the most recent taskDateTime.   There can be multiple records per taskID.   A task could have a record with a state of "started" and "active" that have the same taskDatetime, in which case I want the "active" record.  

sample data    

taskID = 1, taskState=active, taskDatetime=9/1/2015
taskID = 1, taskState=started, taskDatetime=9/1/2015
taskID = 1, taskState=active, taskDatetime=7/1/2015
taskID = 1, taskState=started, taskDatetime=7/1/2015

taskID = 2, taskState=active, taskDatetime=9/2/2015
taskID = 2, taskState=started, taskDatetime=7/2/2015
taskID = 3, taskState=started, taskDatetime=9/5/2015
taskID = 4, taskState=started, taskDatetime=9/6/2015

taskID = 5, taskState=active, taskDatetime=8/1/2015
taskID = 5, taskState=started, taskDatetime=8/1/2015

I want a these 5 records:

taskID = 1, taskState=active, taskDatetime=9/1/2015
taskID = 2, taskState=active, taskDatetime=9/2/2015
taskID = 3, taskState=started, taskDatetime=9/5/2015
taskID = 4, taskState=started, taskDatetime=9/6/2015
taskID = 5, taskState=active, taskDatetime=8/1/2015
LVL 1
HLRosenbergerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ryan ChongCommented:
try:
select a.taskID, a.taskState, a.taskDatetime
from
(
select a.*,
row_number() over (partition by a.taskID order by a.taskDatetime desc, a.taskState ) idx
 from yourTable a
) a where a.idx = 1
order by a.taskID

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
HLRosenbergerAuthor Commented:
thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.