2014-10-12 59 views
0

我有兩個表具有以下結構高性能TSQL檢索數據

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

我想檢索該數據爲每個人:

行動,一個人是從去年第二個人數行動 這是對第一人稱

當前查詢

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 

這個查詢性能不好,我需要更好的一個。

+0

請告訴我們一些關於您的輸入表和您期望的輸出。另外,表格有多少行? – 2014-10-12 06:53:54

+0

你想要「前1個日期」來獲取第一個人的最後一個行動日期嗎? – 2014-10-12 06:56:48

回答

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