通过maxdate对多个记录求和

时间:2012-09-24 15:55:32

标签: tsql sum maxdate

我有一张包含以下数据的表

Bldg        Suit    SQFT     Date
1           1       1,000    9/24/2012              
1           1       1,500    12/31/2011
1           2       800      8/31/2012
1           2       500      10/1/2005

我想编写一个查询,将每个套装记录的最大日期相加,因此所需的结果将是1,800,并且必须位于一个单元格/行中。这最终将成为子查询的一部分,到目前为止,我只是没有达到我对查询的期望。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以使用以下内容(请参阅SQL Fiddle with Demo):

select sum(t1.sqft) Total
from yourtable t1
inner join
(
  select max(dt) mxdt, suit, bldg
  from yourtable
  group by suit, bldg
) t2
  on t1.dt = t2.mxdt
  and t1.bldg = t2.bldg
  and t1.suit = t2.suit

答案 1 :(得分:0)

; With Data As
(
    Select Bldg, Suit, SQFT, Row_Number() Over (Partition By Bldg, Suit Order By Date DESC) As RowID
    From   YourTableNameHere
)
Select Bldg, Sum(SQFT) As TotalSQFT
From   Data
Where  RowId = 1
Group By Bldg