I have a table that has a record of all of the work orders that have been performed. there are two types of orders. Installs and Trouble Calls. My query is to find all of the trouble calls that have taken place within 30 days of an install and match that trouble call (TC) to the proper Install (IN). So the Trouble Call date has to happen after the install but no more than 30 days after. Additionally if there are two installs and two trouble calls for the same account all within 30 days and they happen in order the results have to reflect that. The problem I am having is I am getting an Install order matching to two different Trouble Calls (TC) and a Trouble Call(TC) that is matching to two different Installs(IN)
In the example on SQL Fiddle pay close attention to the install order number 1234567810 and the Trouble Call order number 1234567890 and you will see the issue I am having.
For those that don't want to review what is on the SQL Fiddle here is the example
create table workorders
(
WorkOrderNumber varchar(10) not null,
AccountNumber varchar(10) not null,
JobType varchar(2) not null,
ScheduledDate date not null
)
insert into workorders values ('1234567890','666','TC','12/12/2015')
insert into workorders values ('1234567820','666','IN','12/11/2015')
insert into workorders values ('1234567810','666','IN','12/01/2015')
insert into workorders values ('1234567830','666','TC','12/05/2015')
insert into workorders values ('1234567822','777','IN','11/11/2015')
insert into workorders values ('1234567444','777','TC','10/20/2015')
insert into workorders values ('1234567333','777','TC','08/15/2015')
insert into workorders values ('1234567777','555','TC','04/21/2015')
insert into workorders values ('1234568888','555','IN','06/12/2015')
insert into workorders values ('1234566666','555','IN','06/14/2015')
insert into workorders values ('1234544444','555','IN','07/15/2015')
insert into workorders values ('1234999999','555','TC','06/13/2015')
insert into workorders values ('1234562222','555','TC','12/12/2015')
select b.accountnumber,MAX(b.scheduleddate) as OriginalDate,b.workordernumber as OriginalOrder,b.jobtype as OriginalType,MIN(a.scheduleddate) as NewDate,a.workordernumber as NewOrder,a.jobtype as NewType from (
select workordernumber,accountnumber,jobtype,scheduleddate from workorders where jobtype = 'TC'
) a join
(select workordernumber,accountnumber,jobtype,scheduleddate from workorders where jobtype = 'IN'
) b
on a.accountnumber = b.accountnumber
group by b.accountnumber,b.scheduleddate,b.workordernumber,b.jobtype,a.accountnumber,a.scheduleddate,a.workordernumber,a.jobtype
having MIN(a.scheduleddate) > MAX(b.scheduleddate) and DATEDIFF(day,MAX(b.scheduleddate),MIN(a.scheduleddate)) < 31