Is it possible to re-organize your table(s) so that you have a row for each OpDate/OpCode?
ie:
create table opCodeType
(opCodeTypeID tinyint
,opCodeTypeDesc varchar(50))
go
create table myTable
(PatientID int
,Opdate datetime
,OpCode int
,OpCodeTypeID tinyint references opCodeType(opCodeTypeID))
go
insert opCodeType values (1, 'Primary')
insert opCodeType values (2, 'Secondary')
go
--then your query could be something like:
select patientID
,opDate
,opCode
,opCodeTypeDesc
from myTable a
join (--derived table to get first date for each Patient
select patientID
,min(opDate) opDate
from myTable
group by patientID
) b
on a.patientID = b.patientID
and a.opDate = b.opDate
join opCodeType c
on a.opCodeTypeID = c.opCodeTypeDesc
Be One with the Optimizer
TG