SQL Server 2008中的Sum函数

时间:2014-01-31 13:00:46

标签: sql sql-server

我有一张桌子:

 PropertyID     Amount        
 --------------------------
   1              40                   
   1              20                
   1              10                    
   2              10                 
   2              90            

我想实现:

    PropertyId       Amount   Total_Amount
  ---------------------------------------       
      1                40        70
      1                20        70
      1                10        70
      2                10        100
      2                90        100

使用以下查询:

SELECT  
    PropertyID,
    SUM(Amount),
    SUM(TotalAmount)
FROM 
    yourTable
WHERE 
    EndDate IS NULL
GROUP BY 
    PropertyID

输出:

    PropertyId       Amount   TotalAmount
  -------------------------------------       
      1                70      70
      2                100     100

让我知道如何获得所需的输出...

2 个答案:

答案 0 :(得分:5)

您可以使用窗口功能执行此操作:

select PropertyID, Amount,
       sum(Amount) over (partition by PropertyId) as TotalAmount
from yourtable;

sum()的窗口函数执行以下操作。它计算同一组中行组的amount之和。该组由partition by子句定义,因此具有相同值PropertyId的行位于同一组中。

答案 1 :(得分:0)

SELECT  PropertyID,
    Amount,
    (select sum(yt.Amount)
      from yourTable yt where yt.PropertyID==y.PropertyID and yt.EndDate IS NULL)
    as TotalAmount
    FROM yourTable y
    WHERE y.EndDate IS NULL