如何查询最新记录和汇总结果

时间:2015-06-17 17:07:04

标签: sql aggregate

我有以下表格

表名: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

1 个答案:

答案 0 :(得分: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