2015-06-17 78 views
1

我有一個下表如何查詢最新的記錄和彙總結果

表名:REC

Name | Hits | Month | State  
Joe | 15 | 1  | CA  
Joe | 16 | 2  | CA  
Joe | 12 | 3  | TX 

我想要得到的是與名稱一行,全部命中的總和結果,只有最近的國家。

所以我的結果應該是:

Name | SumHits | RecentState  
Joe | 43  | TX 

這裏是我到目前爲止有:

這個查詢讓我命中的名稱和金額:

select Name, sum(Hits) 
from REC 
Group By Name 

這查詢讓我接近我想要的東西,但它只是在最近一個月(12)而不是我想要的(43)

select a.Name, a.Hits, b.Month, a.State 
from REC as a 
Inner Join (
    select Name, max(Month) as Month 
    from REC 
    Group By Name) as b 
On a.Name = b.Name 
And a.Month = b.Month 
+2

是否使用的是RDBMS? – potashin

回答

1

您可以包括你在你的子查詢總之,像這樣:

select a.Name, b.Total_Hits, b.Month, a.State 
from REC as a 
Inner Join (
    select Name, max(Month) as Month, sum(Hits) as Total_Hits 
    from REC 
    Group By Name) as b 
On a.Name = b.Name 
And a.Month = b.Month