I have quite a complex query that is used to match up certain people to orders (jobs). The problem is all the data that needs to be collected from various tables, and I've tried to consolidate the result sets from the biggest tables into some report tables so I could query off them. The problem is with the way it's written it can still take about 25 minutes to run. I am hoping someone can look at the tables and indexes I have created, and also at the query and see if there's anything I can do to speed this up. I appreciate any help! Sorry I know this is quite a bit of info. Thanks to anyone for taking a look.
Tables created:
/************** Create Traveler table **************/ CREATE TABLE TravelerOrderReportTravs ( TravelerID int NOT NULL , Firstname varchar(255) , Lastname varchar(255) , Email varchar(255) , Email2 varchar(255) , Cell varchar(20) , LastContactAttempt datetime , LastContact datetime , OffAssnDate datetime , FacilityID int , ParentID int , AffiliationID int , BookingCompanyID int , CompleteDate datetime , LicensureRequirementTypeID int , ExpirationDate datetime , LicStateID int , HearsayID int , SpecialtyID int NOT NULL , DisciplineID int NOT NULL , Brand varchar(255) , Recruiter varchar(255) , RecruiterEmail varchar(255) ) CREATE NONCLUSTERED INDEX [IX_TravDiscSpec] ON TravelerOrderReportTravs ( [TravelerID] ASC, [DisciplineID] ASC, [SpecialtyID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY] GO /********* Create Order table **********/ CREATE TABLE TravelerOrderReportOrders ( OrderID int NOT NULL ,FacilityID int NOT NULL ,UnitID int ,DateEntered datetime ,PositionsAvailable int ,StartDate datetime ,EndDate datetime ,UnitName varchar(500) ,ParentID int ,HealthSystem varchar(255) ,AffiliationID int ,FacilityName varchar(500) ,City varchar(500) ,StateProvinceID varchar(50) ,StateID int ,RegionalDirectorID int ,PrimaryHAMID int ,RegionID int ,DisciplineID int NOT NULL ,SpecialtyID int NOT NULL ,LicensureRequirementTypeID int ,OrderSkillSet varchar(500) ,NumberOfWeeks int ,OrderShifts varchar(255) ,MaxPayrate int ,FileOut int ,JobDescription varchar(max) ,RequiredQualifications varchar(max) ,PreferredQualifications varchar(max) ) CREATE CLUSTERED INDEX [IX_OrderDiscSpec] ON TravelerOrderReportOrders ( [OrderID] ASC, [DisciplineID] ASC, [SpecialtyID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY] GO /****** CREATE results table ***************/ CREATE TABLE TravelerOrderReportMatching ( TravelerID int ,FirstName varchar(255) ,LastName varchar(255) ,Email varchar(255) ,Email2 varchar(255) ,Cell varchar(255) ,OrderID varchar(255) ,OrderSkillSet varchar(255) ,FacilityName varchar(255) ,City varchar(255) ,StateProvinceID varchar(255) ,ParentID int ,HealthSystem varchar(255) ,UnitName varchar(255) ,LastContact datetime ,OrderStart datetime ,OrderEnd datetime ,Tag varchar(255) ,CompleteDate datetime ,Recruiter varchar(255) ,Brand varchar(255) ,RecruiterEmail varchar(255) ,NumberOfWeeks int ,OrderShifts varchar(255) ,MaxPayrate varchar(255) ,FileOut int ,JobDescription varchar(max) ,RequiredQualifications varchar(max) ,PreferredQualifications varchar(max)) CREATE NONCLUSTERED INDEX [IX_TravOrder] ON TravelerOrderReportMatching ( [TravelerID] ASC, [OrderID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY] GO /*********** Build results table **************/ CREATE TABLE TravelerOrderReportResults ( TravelerID int ,FirstName varchar(255) ,LastName varchar(255) ,Email varchar(255) ,Email2 varchar(255) ,Cell varchar(255) ,OrderID varchar(255) ,OrderSkillSet varchar(255) ,FacilityName varchar(255) ,City varchar(255) ,StateProvinceID varchar(255) ,ParentID int ,HealthSystem varchar(255) ,UnitName varchar(255) ,LastContact datetime ,OrderStart datetime ,OrderEnd datetime ,Tag varchar(255) ,CompleteDate datetime ,Recruiter varchar(255) ,Brand varchar(255) ,RecruiterEmail varchar(255) ,NumberOfWeeks int ,OrderShifts varchar(255) ,MaxPayrate varchar(255) ,FileOut int ,JobDescription varchar(max) ,RequiredQualifications varchar(max) ,PreferredQualifications varchar(max)) CREATE NONCLUSTERED INDEX [IX_TravOrder] ON TravelerOrderReportResults ( [TravelerID] ASC, [OrderID] ASC, [Brand] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY] GO CREATE NONCLUSTERED INDEX [IX_Dates] ON TravelerOrderReportResults ( [TravelerID] ASC, [OrderID] ASC, [CompleteDate] ASC, [LastContact] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY] GO
There are other tables involved in the query below, but they are smaller reference tables. When I break the time down in batches, here is what I find. The section commented as:
Open Order Finder - 0 secs
Available Traveler Finder - 22 secs
MATCHING queries (all in one because there are UNIONs - 10mins 47secs
Generate results of match - 11mins 49secs
Query for final results - 1min 48secs
So I am not good with indexes so I don't know if the indexes on the tables are no good. And plus there is an OR in the MATCHING query joins. Is that really bad? The result set at the end is about 1.3 million rows.
I know this is a lot, so thanks again to anyone that takes a look!
Entire Query:
/********************************************/ SET NOCOUNT ON SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED /******* OPEN ORDER FINDER **********/ INSERT INTO TravelerOrderReportOrders SELECT DISTINCT o.OrderID ,f.FacilityID ,u.UnitID ,o.DateEntered ,o.PositionsAvailable ,ISNULL(o.StartDate, GETDATE() +1) StartDate ,o.EndDate ,u.[Name] UnitName ,f.ParentID ,hs.Name HealthSystem ,f.AffiliationID ,f.Name FacilityName ,f.City ,f.StateProvinceID ,st.StateNumber StateID ,o.RegionalDirectorID ,o.PrimaryHAMID ,o.RegionID ,ods.DisciplineID ,ods.SpecialtyID ,d.LicensureRequirementTypeID ,d.Abbreviation +'-'+s.[Description] OrderSkillSet ,o.NumberOfWeeks ,REVERSE(STUFF(REVERSE(( SELECT osl.Description + ', ' AS [text()] FROM OrderShift os JOIN OrderShiftList osl ON os.OrderShiftListID = osl.ID WHERE os.OrderID = o.OrderID FOR XML PATH ('') )), 1, 2, '') ) OrderShifts ,o.MaxPayrate ,o.PendingFiles FileOut ,o.JobDescription ,o.RequiredQualifications ,o.PreferredQualifications FROM Orders o JOIN Unit u ON o.unitid = u.unitid JOIN Facility f ON u.facilityid = f.facilityid --LEFT JOIN HealthSystem hs ON f.ParentID = hs.HealthSystemID -- AND f.BestBetsID = 30 -- EMR JOIN StateProvince st ON st.ID = f.StateProvinceID JOIN AMNDivisionType adt on f.AMNdivisiontypeid = adt.id JOIN OrderDiscSpec ods ON o.orderid = ods.orderid JOIN Discipline d ON ods.DisciplineID = d.ID JOIN Specialty s ON ods.SpecialtyID = s.ID WHERE o.positionsavailable > 0 AND ISNULL(o.StartDate, GETDATE() +1) > GETDATE() AND o.MaxFilesSent <> 'Y' /********** AVAILABLE TRAVELER FINDER *********/ INSERT INTO TravelerOrderReportTravs SELECT DISTINCT t.TravelerID , t.Firstname , t.Lastname , tcd.Email , tcd.Email2 , cell.PhoneNumber Cell , ISNULL(lca.LastContactAttempt, '1/1/1900') LastContactAttempt , ISNULL(lc.LastContact, '1/1/1900') LastContact , ISNULL(OnAssn.EndDate, GETDATE()) OffAssnDate , FacMatch.FacilityID , FacMatch.ParentID , FacMatch.AffiliationID , FacMatch.BookingCompanyID , FacMatch.EndDate AS CompleteDate , lic.LicensureRequirementTypeID , lic.ExpirationDate , lic.LicStateID , lic.HearsayID , tds.SpecialtyID , tds.DisciplineID , c.Description AS Brand , e.FirstName +' '+ e.LastName Recruiter , e.Email RecruiterEmail FROM Traveler t JOIN TravelerCompanyData tcd ON t.travelerid = tcd.travelerid AND tcd.Statusid IN (2,10,1,11)-- a, aw/a, p, pw/a JOIN Company c ON tcd.CompanyID = c.ID JOIN Employee e ON e.EmployeeID = tcd.RecruiterID JOIN TravelerSpecialty tds ON tds.TravelerID = t.TravelerID JOIN Specialty s ON s.ID = tds.SpecialtyID JOIN Discipline d ON d.ID = tds.DisciplineID LEFT JOIN travelerphone cell ON t.travelerid = cell.travelerid AND tcd.companyid = cell.companyid AND cell.phonetypeid = 6 LEFT JOIN ( SELECT lc.TravelerID ,lc.CompanyID ,max(lc.DateCreated) LastContactAttempt FROM CTIActivityHistory lc JOIN CTIActivityType cat ON lc.ctiactivitytypeid = cat.ctiactivitytypeid AND cat.CTICallTypeID = 1 --outbound WHERE lc.CompanyID IS NOT NULL GROUP BY lc.TravelerID ,lc.CompanyID )lca ON lca.TravelerID = tcd.TravelerID AND lca.CompanyID = tcd.CompanyID LEFT JOIN ( SELECT lc.TravelerID ,lc.CompanyID ,max(lc.DateCreated) LastContact FROM CTIActivityHistory lc JOIN CTIActivityType cat ON lc.ctiactivitytypeid = cat.ctiactivitytypeid AND cat.CTICallOutcomeID = 2 --Contacted WHERE lc.CompanyID IS NOT NULL GROUP BY lc.TravelerID ,lc.CompanyID )lc ON lc.TravelerID = tcd.TravelerID AND lc.CompanyID = tcd.CompanyID JOIN ( SELECT p.TravelerID ,f.FacilityID ,f.ParentID ,f.AffiliationID ,p.BookingCompanyID ,max(p.EndDate) EndDate FROM Placement p JOIN Facility f ON f.FacilityID = p.FacilityID WHERE p.ActivityTypeID = 5 GROUP BY p.TravelerID ,f.FacilityID ,f.ParentID ,f.AffiliationID ,p.BookingCompanyID ) FacMatch ON t.Travelerid = FacMatch.Travelerid AND tcd.CompanyID = FacMatch.BookingCompanyID LEFT JOIN ( SELECT p.TravelerID , max(p.enddate) EndDate FROM Placement p WHERE p.Activitystatusid IN (14,15,17,18,23) GROUP BY p.TravelerID ) OnAssn ON t.Travelerid = OnAssn.Travelerid LEFT JOIN (SELECT DISTINCT tr.TravelerID ,d.LicensureRequirementTypeID ,d.ID DisciplineID ,d.Abbreviation Discipline ,tr.StateID LicStateID ,tr.HearsayID ,max(tr.ExpirationDate) ExpirationDate FROM TravelerRequirement tr JOIN Discipline d ON tr.RequirementTypeID = d.LicensureRequirementTypeID GROUP BY tr.TravelerID ,d.LicensureRequirementTypeID ,d.ID ,d.Abbreviation ,tr.StateID ,tr.HearsayID ) lic ON lic.TravelerID = tds.TravelerID AND lic.DisciplineID = tds.DisciplineID /******* MATCHING Worked at Facility ***************/ SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED INSERT INTO TravelerOrderReportMatching SELECT DISTINCT t.TravelerID , t.FirstName , t.LastName , t.Email , t.Email2 , t.Cell , o.OrderID , d.Abbreviation + '-' + s.[Description] AS OrderSkillSet , o.FacilityName , o.City , o.StateProvinceID , o.ParentID , o.HealthSystem , o.UnitName , t.LastContact , convert(varchar,o.StartDate,101) OrderStart , convert(varchar,o.EndDate,101) OrderEnd , 'Worked At Facility' as Tag , CASE WHEN t.CompleteDate = '1900-01-01' THEN '' ELSE t.CompleteDate END CompleteDate ,t.Recruiter ,t.Brand ,t.RecruiterEmail ,o.NumberOfWeeks ,o.OrderShifts ,o.MaxPayrate ,o.FileOut ,o.JobDescription ,o.RequiredQualifications ,o.PreferredQualifications FROM TravelerOrderReportTravs t JOIN Discipline d ON t.DisciplineID = d.ID JOIN Specialty s ON t.SpecialtyID = s.ID LEFT JOIN ( SELECT DISTINCT ms.DisciplineID ,COALESCE(ms.SpecialtyID, x.SpecialtyID) SpecialtyID ,ms.SimilarDisciplineID ,COALESCE(ms.SimilarSpecialtyID, x.SpecialtyID) SimilarSpecialtyID FROM MapSpecialty ms LEFT JOIN Discipline d ON ms.DisciplineID = d.ID LEFT JOIN Specialty s ON ms.SpecialtyID = s.ID LEFT JOIN ( SELECT DisciplineID, ID SpecialtyID FROM MapSpecialty ms CROSS JOIN Specialty s ) x ON ms.DisciplineID = x.DisciplineID AND ms.SpecialtyID IS NULL --ORDER BY 1,2 ) ms ON t.DisciplineID = ms.DisciplineID AND t.SpecialtyID = ms.SpecialtyID JOIN TravelerOrderReportOrders o ON ( o.DisciplineID = t.DisciplineID AND o.SpecialtyID = t.SpecialtyID ) OR ( ms.SimilarDisciplineID = o.DisciplineID AND ms.SimilarSpecialtyID = o.SpecialtyID ) WHERE ( ISNULL(t.OffAssnDate, o.StartDate - 1) < o.StartDate AND o.FacilityID = t.FacilityID ) /******* MATCHING Worked at Health System *************/ UNION SELECT DISTINCT t.TravelerID , t.FirstName , t.LastName , t.Email , t.Email2 , t.Cell , o.OrderID , d.Abbreviation + '-' + s.[Description] AS OrderSkillSet , o.FacilityName , o.City , o.StateProvinceID , o.ParentID , o.HealthSystem , o.UnitName , t.LastContact , convert(varchar,o.StartDate,101) OrderStart , convert(varchar,o.EndDate,101) OrderEnd , 'Worked At Health System' as Tag , CASE WHEN t.CompleteDate = '1900-01-01' THEN '' ELSE t.CompleteDate END CompleteDate ,t.Recruiter ,t.Brand ,t.RecruiterEmail ,o.NumberOfWeeks ,o.OrderShifts ,o.MaxPayrate ,o.FileOut ,o.JobDescription ,o.RequiredQualifications ,o.PreferredQualifications FROM TravelerOrderReportTravs t JOIN Discipline d ON t.DisciplineID = d.ID JOIN Specialty s ON t.SpecialtyID = s.ID LEFT JOIN ( SELECT DISTINCT ms.DisciplineID ,COALESCE(ms.SpecialtyID, x.SpecialtyID) SpecialtyID ,ms.SimilarDisciplineID ,COALESCE(ms.SimilarSpecialtyID, x.SpecialtyID) SimilarSpecialtyID FROM MapSpecialty ms LEFT JOIN Discipline d ON ms.DisciplineID = d.ID LEFT JOIN Specialty s ON ms.SpecialtyID = s.ID LEFT JOIN ( SELECT DisciplineID, ID SpecialtyID FROM MapSpecialty ms CROSS JOIN Specialty s ) x ON ms.DisciplineID = x.DisciplineID AND ms.SpecialtyID IS NULL ) ms ON t.DisciplineID = ms.DisciplineID AND t.SpecialtyID = ms.SpecialtyID JOIN TravelerOrderReportOrders o ON ( o.DisciplineID = t.DisciplineID AND o.SpecialtyID = t.SpecialtyID ) OR ( ms.SimilarDisciplineID = o.DisciplineID AND ms.SimilarSpecialtyID = o.SpecialtyID ) WHERE ISNULL(t.OffAssnDate, o.StartDate - 1) < o.StartDate AND o.ParentID = t.ParentID AND o.ParentID NOT IN (SELECT HealthSystemID FROM HealthSystem WHERE Name LIKE '%single%') /****** MATCHING Worked at Contract Affiliate ******/ UNION SELECT DISTINCT t.TravelerID , t.FirstName , t.LastName , t.Email , t.Email2 , t.Cell , o.OrderID , d.Abbreviation + '-' + s.[Description] AS OrderSkillSet , o.FacilityName , o.City , o.StateProvinceID , o.ParentID , o.HealthSystem , o.UnitName , t.LastContact , convert(varchar,o.StartDate,101) OrderStart , convert(varchar,o.EndDate,101) OrderEnd , 'Worked At Contract Affiliate' as Tag , CASE WHEN t.CompleteDate = '1900-01-01' THEN '' ELSE t.CompleteDate END CompleteDate ,t.Recruiter ,t.Brand ,t.RecruiterEmail ,o.NumberOfWeeks ,o.OrderShifts ,o.MaxPayrate ,o.FileOut ,o.JobDescription ,o.RequiredQualifications ,o.PreferredQualifications FROM TravelerOrderReportTravs t JOIN Discipline d ON t.DisciplineID = d.ID JOIN Specialty s ON t.SpecialtyID = s.ID LEFT JOIN ( SELECT DISTINCT ms.DisciplineID ,COALESCE(ms.SpecialtyID, x.SpecialtyID) SpecialtyID ,ms.SimilarDisciplineID ,COALESCE(ms.SimilarSpecialtyID, x.SpecialtyID) SimilarSpecialtyID FROM MapSpecialty ms LEFT JOIN Discipline d ON ms.DisciplineID = d.ID LEFT JOIN Specialty s ON ms.SpecialtyID = s.ID LEFT JOIN ( SELECT DisciplineID, ID SpecialtyID FROM MapSpecialty ms CROSS JOIN Specialty s ) x ON ms.DisciplineID = x.DisciplineID AND ms.SpecialtyID IS NULL --ORDER BY 1,2 ) ms ON t.DisciplineID = ms.DisciplineID AND t.SpecialtyID = ms.SpecialtyID JOIN TravelerOrderReportOrders o ON ( o.DisciplineID = t.DisciplineID AND o.SpecialtyID = t.SpecialtyID ) OR ( ms.SimilarDisciplineID = o.DisciplineID AND ms.SimilarSpecialtyID = o.SpecialtyID ) WHERE (ISNULL(t.OffAssnDate, o.StartDate - 1) < o.StartDate AND o.AffiliationID = t.AffiliationID ) /******** MATCHING Active License *********/ UNION SELECT DISTINCT t.TravelerID , t.FirstName , t.LastName , t.Email , t.Email2 , t.Cell , o.OrderID , d.Abbreviation + '-' + s.[Description] AS OrderSkillSet , o.FacilityName , o.City , o.StateProvinceID , o.ParentID , o.HealthSystem , o.UnitName , t.LastContact , convert(varchar,o.StartDate,101) OrderStart , convert(varchar,o.EndDate,101) OrderEnd , 'Active License' as Tag , CASE WHEN t.CompleteDate = '1900-01-01' THEN '' ELSE t.CompleteDate END CompleteDate ,t.Recruiter ,t.Brand ,t.RecruiterEmail ,o.NumberOfWeeks ,o.OrderShifts ,o.MaxPayrate ,o.FileOut ,o.JobDescription ,o.RequiredQualifications ,o.PreferredQualifications FROM TravelerOrderReportTravs t JOIN Discipline d ON t.DisciplineID = d.ID JOIN Specialty s ON t.SpecialtyID = s.ID LEFT JOIN ( SELECT DISTINCT ms.DisciplineID ,COALESCE(ms.SpecialtyID, x.SpecialtyID) SpecialtyID ,ms.SimilarDisciplineID ,COALESCE(ms.SimilarSpecialtyID, x.SpecialtyID) SimilarSpecialtyID FROM MapSpecialty ms LEFT JOIN Discipline d ON ms.DisciplineID = d.ID LEFT JOIN Specialty s ON ms.SpecialtyID = s.ID LEFT JOIN ( SELECT DisciplineID, ID SpecialtyID FROM MapSpecialty ms CROSS JOIN Specialty s ) x ON ms.DisciplineID = x.DisciplineID AND ms.SpecialtyID IS NULL --ORDER BY 1,2 ) ms ON t.DisciplineID = ms.DisciplineID AND t.SpecialtyID = ms.SpecialtyID JOIN TravelerOrderReportOrders o ON ( o.DisciplineID = t.DisciplineID AND o.SpecialtyID = t.SpecialtyID ) OR ( ms.SimilarDisciplineID = o.DisciplineID AND ms.SimilarSpecialtyID = o.SpecialtyID ) WHERE ISNULL(t.OffAssnDate, o.StartDate - 1) < o.StartDate AND o.LicensureRequirementTypeID = t.LicensureRequirementTypeID AND o.StateID = t.LicStateID AND t.ExpirationDate > GETDATE() AND t.HearsayID <> 1 /********* MATCHING Expired License *********/ UNION SELECT DISTINCT t.TravelerID , t.FirstName , t.LastName , t.Email , t.Email2 , t.Cell , o.OrderID , d.Abbreviation + '-' + s.[Description] AS OrderSkillSet , o.FacilityName , o.City , o.StateProvinceID , o.ParentID , o.HealthSystem , o.UnitName , t.LastContact , convert(varchar,o.StartDate,101) OrderStart , convert(varchar,o.EndDate,101) OrderEnd , 'Expired License' as Tag , CASE WHEN t.CompleteDate = '1900-01-01' THEN '' ELSE t.CompleteDate END CompleteDate ,t.Recruiter ,t.Brand ,t.RecruiterEmail ,o.NumberOfWeeks ,o.OrderShifts ,o.MaxPayrate ,o.FileOut ,o.JobDescription ,o.RequiredQualifications ,o.PreferredQualifications FROM TravelerOrderReportTravs t JOIN Discipline d ON t.DisciplineID = d.ID JOIN Specialty s ON t.SpecialtyID = s.ID LEFT JOIN ( SELECT DISTINCT ms.DisciplineID ,COALESCE(ms.SpecialtyID, x.SpecialtyID) SpecialtyID ,ms.SimilarDisciplineID ,COALESCE(ms.SimilarSpecialtyID, x.SpecialtyID) SimilarSpecialtyID FROM MapSpecialty ms LEFT JOIN Discipline d ON ms.DisciplineID = d.ID LEFT JOIN Specialty s ON ms.SpecialtyID = s.ID LEFT JOIN ( SELECT DisciplineID, ID SpecialtyID FROM MapSpecialty ms CROSS JOIN Specialty s ) x ON ms.DisciplineID = x.DisciplineID AND ms.SpecialtyID IS NULL --ORDER BY 1,2 ) ms ON t.DisciplineID = ms.DisciplineID AND t.SpecialtyID = ms.SpecialtyID JOIN TravelerOrderReportOrders o ON ( o.DisciplineID = t.DisciplineID AND o.SpecialtyID = t.SpecialtyID ) OR ( ms.SimilarDisciplineID = o.DisciplineID AND ms.SimilarSpecialtyID = o.SpecialtyID ) WHERE ISNULL(t.OffAssnDate, o.StartDate - 1) < o.StartDate AND o.LicensureRequirementTypeID = t.LicensureRequirementTypeID AND o.StateID = t.LicStateID AND t.ExpirationDate < GETDATE() AND t.HearsayID <> 1 /********* MATCHING Active Hearsay License *********/ UNION SELECT DISTINCT t.TravelerID , t.FirstName , t.LastName , t.Email , t.Email2 , t.Cell , o.OrderID , d.Abbreviation + '-' + s.[Description] AS OrderSkillSet , o.FacilityName , o.City , o.StateProvinceID , o.ParentID , o.HealthSystem , o.UnitName , t.LastContact , convert(varchar,o.StartDate,101) OrderStart , convert(varchar,o.EndDate,101) OrderEnd , 'Active Hearsay License' as Tag , CASE WHEN t.CompleteDate = '1900-01-01' THEN '' ELSE t.CompleteDate END CompleteDate ,t.Recruiter ,t.Brand ,t.RecruiterEmail ,o.NumberOfWeeks ,o.OrderShifts ,o.MaxPayrate ,o.FileOut ,o.JobDescription ,o.RequiredQualifications ,o.PreferredQualifications FROM TravelerOrderReportTravs t JOIN Discipline d ON t.DisciplineID = d.ID JOIN Specialty s ON t.SpecialtyID = s.ID LEFT JOIN ( SELECT DISTINCT ms.DisciplineID ,COALESCE(ms.SpecialtyID, x.SpecialtyID) SpecialtyID ,ms.SimilarDisciplineID ,COALESCE(ms.SimilarSpecialtyID, x.SpecialtyID) SimilarSpecialtyID FROM MapSpecialty ms LEFT JOIN Discipline d ON ms.DisciplineID = d.ID LEFT JOIN Specialty s ON ms.SpecialtyID = s.ID LEFT JOIN ( SELECT DisciplineID, ID SpecialtyID FROM MapSpecialty ms CROSS JOIN Specialty s ) x ON ms.DisciplineID = x.DisciplineID AND ms.SpecialtyID IS NULL --ORDER BY 1,2 ) ms ON t.DisciplineID = ms.DisciplineID AND t.SpecialtyID = ms.SpecialtyID JOIN TravelerOrderReportOrders o ON ( o.DisciplineID = t.DisciplineID AND o.SpecialtyID = t.SpecialtyID ) OR ( ms.SimilarDisciplineID = o.DisciplineID AND ms.SimilarSpecialtyID = o.SpecialtyID ) WHERE ISNULL(t.OffAssnDate, o.StartDate - 1) < o.StartDate AND o.LicensureRequirementTypeID = t.LicensureRequirementTypeID AND o.StateID = t.LicStateID AND t.ExpirationDate > GETDATE() AND t.HearsayID = 1 /********* MATCHING Expired Hearsay License ********/ UNION SELECT DISTINCT t.TravelerID , t.FirstName , t.LastName , t.Email , t.Email2 , t.Cell , o.OrderID , d.Abbreviation + '-' + s.[Description] AS OrderSkillSet , o.FacilityName , o.City , o.StateProvinceID , o.ParentID , o.HealthSystem , o.UnitName , t.LastContact , convert(varchar,o.StartDate,101) OrderStart , convert(varchar,o.EndDate,101) OrderEnd , 'Expired Hearsay License' as Tag , CASE WHEN t.CompleteDate = '1900-01-01' THEN '' ELSE t.CompleteDate END CompleteDate ,t.Recruiter ,t.Brand ,t.RecruiterEmail ,o.NumberOfWeeks ,o.OrderShifts ,o.MaxPayrate ,o.FileOut ,o.JobDescription ,o.RequiredQualifications ,o.PreferredQualifications FROM TravelerOrderReportTravs t JOIN Discipline d ON t.DisciplineID = d.ID JOIN Specialty s ON t.SpecialtyID = s.ID LEFT JOIN ( SELECT DISTINCT ms.DisciplineID ,COALESCE(ms.SpecialtyID, x.SpecialtyID) SpecialtyID ,ms.SimilarDisciplineID ,COALESCE(ms.SimilarSpecialtyID, x.SpecialtyID) SimilarSpecialtyID FROM MapSpecialty ms LEFT JOIN Discipline d ON ms.DisciplineID = d.ID LEFT JOIN Specialty s ON ms.SpecialtyID = s.ID LEFT JOIN ( SELECT DisciplineID, ID SpecialtyID FROM MapSpecialty ms CROSS JOIN Specialty s ) x ON ms.DisciplineID = x.DisciplineID AND ms.SpecialtyID IS NULL --ORDER BY 1,2 ) ms ON t.DisciplineID = ms.DisciplineID AND t.SpecialtyID = ms.SpecialtyID JOIN TravelerOrderReportOrders o ON ( o.DisciplineID = t.DisciplineID AND o.SpecialtyID = t.SpecialtyID ) OR ( ms.SimilarDisciplineID = o.DisciplineID AND ms.SimilarSpecialtyID = o.SpecialtyID ) WHERE ISNULL(t.OffAssnDate, o.StartDate - 1) < o.StartDate AND o.LicensureRequirementTypeID = t.LicensureRequirementTypeID AND o.StateID = t.LicStateID AND t.ExpirationDate < GETDATE() AND t.HearsayID = 1 /********* MATCHING Active Compact License ********/ UNION SELECT DISTINCT t.TravelerID , t.FirstName , t.LastName , t.Email , t.Email2 , t.Cell , o.OrderID , d.Abbreviation + '-' + s.[Description] AS OrderSkillSet , o.FacilityName , o.City , o.StateProvinceID , o.ParentID , o.HealthSystem , o.UnitName , t.LastContact , convert(varchar,o.StartDate,101) OrderStart , convert(varchar,o.EndDate,101) OrderEnd , 'Active Compact License' as Tag , CASE WHEN t.CompleteDate = '1900-01-01' THEN '' ELSE t.CompleteDate END CompleteDate ,t.Recruiter ,t.Brand ,t.RecruiterEmail ,o.NumberOfWeeks ,o.OrderShifts ,o.MaxPayrate ,o.FileOut ,o.JobDescription ,o.RequiredQualifications ,o.PreferredQualifications FROM TravelerOrderReportTravs t JOIN Discipline d ON t.DisciplineID = d.ID JOIN Specialty s ON t.SpecialtyID = s.ID LEFT JOIN ( SELECT DISTINCT ms.DisciplineID ,COALESCE(ms.SpecialtyID, x.SpecialtyID) SpecialtyID ,ms.SimilarDisciplineID ,COALESCE(ms.SimilarSpecialtyID, x.SpecialtyID) SimilarSpecialtyID FROM MapSpecialty ms LEFT JOIN Discipline d ON ms.DisciplineID = d.ID LEFT JOIN Specialty s ON ms.SpecialtyID = s.ID LEFT JOIN ( SELECT DisciplineID, ID SpecialtyID FROM MapSpecialty ms CROSS JOIN Specialty s ) x ON ms.DisciplineID = x.DisciplineID AND ms.SpecialtyID IS NULL --ORDER BY 1,2 ) ms ON t.DisciplineID = ms.DisciplineID AND t.SpecialtyID = ms.SpecialtyID JOIN TravelerOrderReportOrders o ON ( o.DisciplineID = t.DisciplineID AND o.SpecialtyID = t.SpecialtyID ) OR ( ms.SimilarDisciplineID = o.DisciplineID AND ms.SimilarSpecialtyID = o.SpecialtyID ) WHERE ISNULL(t.OffAssnDate, o.StartDate - 1) < o.StartDate AND o.LicensureRequirementTypeID = t.LicensureRequirementTypeID AND o.StateID = t.LicStateID AND t.LicStateID IN (SELECT StateNumber FROM StateProvince s JOIN LicenseBoard lb ON s.ID = lb.StateProvinceID WHERE CompactState = 'Y') AND t.ExpirationDate > GETDATE() AND t.HearsayID = 1 /********* MATCHING Expired Compact License ********/ UNION SELECT DISTINCT t.TravelerID , t.FirstName , t.LastName , t.Email , t.Email2 , t.Cell , o.OrderID , d.Abbreviation + '-' + s.[Description] AS OrderSkillSet , o.FacilityName , o.City , o.StateProvinceID , o.ParentID , o.HealthSystem , o.UnitName , t.LastContact , convert(varchar,o.StartDate,101) OrderStart , convert(varchar,o.EndDate,101) OrderEnd , 'Expired Compact License' as Tag , CASE WHEN t.CompleteDate = '1900-01-01' THEN '' ELSE t.CompleteDate END CompleteDate ,t.Recruiter ,t.Brand ,t.RecruiterEmail ,o.NumberOfWeeks ,o.OrderShifts ,o.MaxPayrate ,o.FileOut ,o.JobDescription ,o.RequiredQualifications ,o.PreferredQualifications FROM TravelerOrderReportTravs t JOIN Discipline d ON t.DisciplineID = d.ID JOIN Specialty s ON t.SpecialtyID = s.ID LEFT JOIN ( SELECT DISTINCT ms.DisciplineID ,COALESCE(ms.SpecialtyID, x.SpecialtyID) SpecialtyID ,ms.SimilarDisciplineID ,COALESCE(ms.SimilarSpecialtyID, x.SpecialtyID) SimilarSpecialtyID FROM MapSpecialty ms LEFT JOIN Discipline d ON ms.DisciplineID = d.ID LEFT JOIN Specialty s ON ms.SpecialtyID = s.ID LEFT JOIN ( SELECT DisciplineID, ID SpecialtyID FROM MapSpecialty ms CROSS JOIN Specialty s ) x ON ms.DisciplineID = x.DisciplineID AND ms.SpecialtyID IS NULL --ORDER BY 1,2 ) ms ON t.DisciplineID = ms.DisciplineID AND t.SpecialtyID = ms.SpecialtyID JOIN TravelerOrderReportOrders o ON ( o.DisciplineID = t.DisciplineID AND o.SpecialtyID = t.SpecialtyID ) OR ( ms.SimilarDisciplineID = o.DisciplineID AND ms.SimilarSpecialtyID = o.SpecialtyID ) WHERE ISNULL(t.OffAssnDate, o.StartDate - 1) < o.StartDate AND o.LicensureRequirementTypeID = t.LicensureRequirementTypeID AND o.StateID = t.LicStateID AND t.LicStateID IN (SELECT StateNumber FROM StateProvince s JOIN LicenseBoard lb ON s.ID = lb.StateProvinceID WHERE CompactState = 'Y') AND t.ExpirationDate < GETDATE() AND t.HearsayID = 1 /************* Generate results of match *************/ INSERT INTO #Results2 SELECT DISTINCT * FROM #Results r1 WHERE Tag = 'Worked At Facility' UNION SELECT * FROM #Results r2 WHERE Tag = 'Worked At Health System' AND NOT EXISTS (SELECT 1 FROM #Results WHERE Tag = 'Worked At Facility' AND TravelerID = r2.TravelerID AND OrderID = r2.OrderID) UNION SELECT DISTINCT * FROM #Results r3 WHERE Tag = 'Worked At Contract Affiliate' AND NOT EXISTS (SELECT 1 FROM #Results WHERE Tag IN ( 'Worked At Facility','Worked At Health System') AND TravelerID = r3.TravelerID AND OrderID = r3.OrderID) UNION SELECT DISTINCT * FROM #Results r4 WHERE Tag = 'Active License' AND NOT EXISTS (SELECT 1 FROM #Results WHERE Tag IN ( 'Worked At Facility','Worked At Health System','Worked At Contract Affiliate') AND TravelerID = r4.TravelerID AND OrderID = r4.OrderID) UNION SELECT DISTINCT * FROM #Results r5 WHERE Tag = 'Expired License' AND NOT EXISTS (SELECT 1 FROM #Results WHERE Tag IN ( 'Worked At Facility','Worked At Health System','Worked At Contract Affiliate','Active License') AND TravelerID = r5.TravelerID AND OrderID = r5.OrderID) UNION SELECT DISTINCT * FROM #Results r6 WHERE Tag = 'Active Hearsay License' AND NOT EXISTS (SELECT 1 FROM #Results WHERE Tag IN ( 'Worked At Facility','Worked At Health System','Worked At Contract Affiliate','Active License','Expired License') AND TravelerID = r6.TravelerID AND OrderID = r6.OrderID) UNION SELECT DISTINCT * FROM #Results r7 WHERE Tag = 'Expired Hearsay License' AND NOT EXISTS (SELECT 1 FROM #Results WHERE Tag IN ( 'Worked At Facility','Worked At Health System','Worked At Contract Affiliate','Active License','Expired License', 'Active Hearsay License') AND TravelerID = r7.TravelerID AND OrderID = r7.OrderID) UNION SELECT DISTINCT * FROM #Results r8 WHERE Tag = 'Active Compact License' AND NOT EXISTS (SELECT 1 FROM #Results WHERE Tag IN ( 'Worked At Facility','Worked At Health System','Worked At Contract Affiliate','Active License','Expired License' ,'Active Hearsay License','Expired Hearsay License') AND TravelerID = r8.TravelerID AND OrderID = r8.OrderID) UNION SELECT DISTINCT * FROM #Results r9 WHERE Tag = 'Expired Compact License' AND NOT EXISTS (SELECT 1 FROM #Results WHERE Tag IN ('Worked At Facility','Worked At Health System','Worked At Contract Affiliate','Active License','Expired License' ,'Active Hearsay License','Expired Hearsay License','Active Compact License') AND TravelerID = r9.TravelerID AND OrderID = r9.OrderID) /*********** Query for final results **********/ SELECT DISTINCT r2.* --INTO --drop table --TravelerOrderReportResults3 FROM TravelerOrderReportResults r2 JOIN TravelerOrderReportResults r3 ON r2.OrderID = r3.OrderID AND r2.CompleteDate = (SELECT max(CompleteDate) FROM TravelerOrderReportResults WHERE OrderID = r2.OrderID AND TravelerID = r2.TravelerID ) AND r2.OrderSkillSet = ( SELECT TOP 1 OrderSkillSet FROM TravelerOrderReportResults WHERE OrderID = r2.OrderID AND TravelerID = r2.TravelerID)