Link to home
Start Free TrialLog in
Avatar of Ali Shah
Ali ShahFlag for United Kingdom of Great Britain and Northern Ireland

asked on

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'),
						 (1,2,'Booked','20180309'),
						 (1,3,'Outstanding','20180308'),
						 (2,1,'Booked','20180310'),
						 (2,2,'Booked','20180309'),
						 (2,2,'Requested','20180308')

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
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ali Shah

ASKER

That is brilliant. Yes that's what i wanted. Thanks a lot
you are a star
Regards,