I have this query:SELECT a.* FROM Unscheduled_Arrival a INNER JOIN (SELECT Person_ID ,[arrival date] ,[leaving date] ,[unique stay id] ,[area code] FROM Unscheduled_Arrival WHERE [area code] != 'AREA_GH' and [leaving date] is not null) b ON a.Person_ID = b.Person_IDWHERE a.[area code] = 'AREA_GH'and a.[arrival date] >= b.[leaving date] and DATEDIFF(DD, b.[leaving date], a.[arrival date]) <=7and DATEDIFF(DD, b.[leaving date], a.[arrival date]) >=0order by a.Person_ID
And what I am trying to do is find instances where a person has arrived back at a different area within 7 days of leaving from a planned visit to any other area different from the last. so lets say we had person ID = 1 and they had had 3 planned visits to one area (not equal to area_gh) in the last 4 months but after the 2nd planned trip to the other area, and before the commencement of the 3rd planned trip to any area not equal to area_gh, they had arrived unscheduled to area_gh, and this unplanned visit was within 7 days of leaving the 2nd last planned visit to any area not equal to area_gh.The query I have shows data from unscheduled arrivals to the area_gh for a person who has also had visits to any area other than area_gh, but each record for unscheduled visits to area_gh duplicates for the amount of times the person has had scheduled visits to any area not equal to area_gh. This is the first problem but is as a result of not having the correct SQL for the refinement of the data.This refinement requires that I return only the data that relates to the unscheduled arrival that is within 7 days of the last scheduled arrival, not duplicate rows of area_gh visits for all the scheduled arrivals. Because my data is showing the data I want but the count is related to the scheduled arrivals I think I need to rewrite the query or alter it.The data is already restricted to a year's worth of data.I just need to find any instances of unscheduled arrivals (for arrival at area_gh) within 7 days of the end of any scheduled arrival (determined using leaving date) to area equal to area_gh.There can be any number of scheduled arrivals and any number of unscheduled arrivals for each person. The [unique stay id] is distinct for each visit so person 1 can have 3 stays, all with a different [unique stay id].Hope someone can suggest a way to do this?ThanksG