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
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.