sqlserver2008中的Sum函数

sqlserver2008中的Sum函数,sql,sql-server,Sql,Sql Server,我有一张桌子: PropertyID Amount -------------------------- 1 40 1 20 1 10 2 10 2 90

我有一张桌子:

 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

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

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

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

sum()
的窗口函数执行以下操作。它计算同一组中多组行的
金额之和。组由
分区依据
子句定义,因此具有相同
属性ID值的行位于同一组中。

您可以使用窗口函数执行此操作:

select PropertyID, Amount,
       sum(Amount) over (partition by PropertyId) as TotalAmount
from yourtable;
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

sum()
的窗口函数执行以下操作。它计算同一组中多组行的
金额之和。组由
分区依据
子句定义,因此具有相同
属性ID值的行在同一组中。

SQL Server的哪个版本?SQL Server的哪个版本?是否应该有分组依据?@Jaques。不应该有
分组依据
。谢谢你注意到了。应该有一个小组吗?@Jaques。不应该有
分组依据
。谢谢你注意到了。
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