0

I have two tables with below structure

Person(ID, Name, ...)
Action(ID, FirstPersonId, SecondPersonId, Date)

I wanna retrieve this data for each person:

Number of action that a person be on second person from last action that be on first person

Current query

Select  Result.Id ,
        (Select Count(*)
            From    Action
            Where   SecondPersonId = Result.Id 
                    AND Date > Result.LastAction)
    From    
            (Select ID ,
                    (   
                        Select Top 1 Date
                            From    Action
                            Where   Action.FirstPersonId = Person.Id
                    ) as LastAction
                From    Person ) As Result

this query has bad performance and i need very better one.

Ram
  • 3,092
  • 10
  • 40
  • 56
Behrooz
  • 2,437
  • 3
  • 21
  • 31

1 Answers1

2
with lastActionPerson as  -- last action for every first person
(select FirstPersonId , max([Date]) as LastActionDate
   from Action
)
select a.SecondPersonId ,count(*)
  from lastActionPerson lap
  join Action a
    on a.SecondPersonId = lap.FirstPersonId --  be on second person
   and a.[Date] > lap.lastActionDate  
 -- you could continue to right join person table to show the person without actions
 group by a.SecondPersonId 
Jaugar Chang
  • 3,176
  • 2
  • 13
  • 23