Ali Shah
asked on
How to select top record based on the state column
Hi EE,
I have got a sample data as
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
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'),
(1,2,'Booked','20180309'),
(1,3,'Outstanding','20180308'),
(2,1,'Booked','20180310'),
(2,2,'Booked','20180309'),
(2,2,'Requested','20180308')
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.
Kindest regards
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
you are a star
Regards,