I am looking for a better way to write this query.
The query uses the results from a CTE created previously which has these columns:
( TravelerID ,FirstName ,LastName ,Company ,PlacementID ,PlacementSkillSet ,StartDate ,EndDate ,WksOnAssignment ,Recruiter ,DisciplineID ,SpecialtyID ,BookingCompanyID )
TravelerID FirstName LastName Company PlacementID StartDate EndDate CompanyID FacilityID 65648 Lori SmithAcme 392605 2/24/03 5/24/03 3 3397 65648 Lori Smith Acme 477950 5/26/03 11/22/033 282 65648 Lori Smith Acme 600089 12/1/03 5/29/04 3 282 65648 Lori Smith Acme 717424 5/30/04 12/4/04 3 282 65648 Lori Smith Acme 832842 12/5/04 2/4/05 3 282
This is a list of all the placements the person has been on. What they want to do is count placements where there is only a gap of one day between the previous placement's EndDate and the new placement's StartDate at the same Facility as one placement. Notice in the list above, PlacementIDs 600089, 717424, and 832842 are all consecutive, so they want them to be one placement. I need to still get the first StartDate and the last EndDate of that series, so it would look like so:
TravelerID FirstName LastName Company PlacementID StartDate EndDate CompanyID FacilityID 65648 Lori Smith Acme 392605 2/24/03 5/24/03 3 3397 65648 Lori Smith Acme 477950 5/26/03 11/22/033 282 65648 Lori Smith Acme 600089 12/1/03 2/04/05 3 282
It could be 2 consecutive placements, or it could be 20 that make up one placement, the amount would vary. My query is joining the same CTE four times to itself, but that would not be reliable (what if there were 5 consecutive placements?).
SELECT v1.TravelerID ,v1.FirstName ,v1.LastName ,v1.Company ,v1.PlacementID ,v1.PlacementSkillSet ,v1.StartDate ,COALESCE(v5.EndDate, v4.EndDate, v3.EndDate, v2.EndDate, v1.EndDate) AS EndDate ,ISNULL(v1.WksOnAssignment,0) + ISNULL(v2.WksOnAssignment,0) + ISNULL(v3.WksOnAssignment,0) + ISNULL(v4.WksOnAssignment,0) AS WksOnAssignment ,v1.Recruiter ,v1.DisciplineID ,v1.SpecialtyID ,v1.BookingCompanyID ,v1.PlacementID ,v2.PlacementID ,v3.PlacementID ,v4.PlacementID FROM CTE_All v1 JOIN CTE_All v2 ON v1.TravelerID = v2.TravelerID AND v1.FacilityID = v2.FacilityID AND v1.StartDate < v2.StartDate AND v1.EndDate < v2.EndDate AND v2.StartDate = v1.EndDate + 1 LEFT JOIN CTE_All v3 ON v3.TravelerID = v2.TravelerID AND v3.FacilityID = v2.FacilityID AND v3.StartDate > v2.StartDate AND v3.EndDate > v2.EndDate AND v3.StartDate = v2.EndDate + 1 LEFT JOIN CTE_All v4 ON v3.TravelerID = v4.TravelerID AND v3.FacilityID = v4.FacilityID AND v3.StartDate < v4.StartDate AND v3.EndDate < v4.EndDate AND v4.StartDate = v3.EndDate + 1 )
I was thinking there should be a smarter way to do this. Please help
Thanks all!!!