How to select top record based on the state column

Hi EE,

I have got a sample data as
DECLARE @data TABLE (ContractId INT, WorkorderId INT, AppointmentState VARCHAR(15), DateCreated DATETIME)
INSERT INTO @data VALUES (1,1,'Requested','20180310'),

select * from @data

Open in new window

In the dataset against the contractid 1 i have got multiple workorderid. I can have Appointment State of Booked, Requested and Outstanding.
1. If the AppointmentState of any workorder is Booked then i want only that record in my result set.
2. If the appointment status dones't contain Booked but if it contains Requested then i want only that record in my result set
3. If all the records of that contractid dont' have Booked and Requested state then i want to display that record only.
4. If there are duplicate states for a contractid for example two states of Booked then i want to get the first record by date created.

I can do this by WHILE loop but was just wondering is there any other way of doing it as the data set contains over 150,000 records and the performance of while loop will be very slow.

Kindest regards
Ali ShahSQL DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

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.

ste5anSenior DeveloperCommented:
If I understand you correctly, then you just need an TOP per GROUP BY, which is easily done with ROWNUMBER(). This is also much faster than a RBAR:

        ContractId INT ,
        WorkorderId INT ,
        AppointmentState VARCHAR(15) ,
        DateCreated DATETIME

VALUES ( 1, 1, 'Requested', '20180310' ) ,
       ( 1, 2, 'Booked', '20180309' ) ,
       ( 1, 3, 'Outstanding', '20180308' ) ,
       ( 2, 1, 'Booked', '20180310' ) ,
       ( 2, 2, 'Booked', '20180309' ) ,
       ( 2, 2, 'Requested', '20180308' ) ,
       ( 3, 2, 'Booked', '20180309' ) ,
       ( 3, 3, 'Outstanding', '20180308' ) ,
       ( 4, 2, 'Requested', '20180308' ) ,
       ( 5, 3, 'Outstanding', '20180308' );

WITH [Data]
            ROW_NUMBER() OVER ( PARTITION BY D.ContractId
                                ORDER BY CASE D.AppointmentState
                                              WHEN 'Booked' THEN 1
                                              WHEN 'Requested' THEN 2
                                              WHEN 'Outstanding' THEN 3
                                              ELSE 999
                                         END ,
                                         D.DateCreated ASC ) AS RN
     FROM   @Data D )
FROM   [Data] D
WHERE  D.RN = 1;

Open in new window

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
Ali ShahSQL DeveloperAuthor Commented:
That is brilliant. Yes that's what i wanted. Thanks a lot
you are a star
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

From novice to tech pro — start learning today.