[英]Sum function in SQL Server 2008
I have a table: 我有一张桌子:
PropertyID Amount
--------------------------
1 40
1 20
1 10
2 10
2 90
I would like to achieve : 我想实现:
PropertyId Amount Total_Amount
---------------------------------------
1 40 70
1 20 70
1 10 70
2 10 100
2 90 100
using below query : 使用以下查询:
SELECT
PropertyID,
SUM(Amount),
SUM(TotalAmount)
FROM
yourTable
WHERE
EndDate IS NULL
GROUP BY
PropertyID
Output: 输出:
PropertyId Amount TotalAmount
-------------------------------------
1 70 70
2 100 100
Let me know how can I get my desired output ... 让我知道如何获得所需的输出...
You can do this using window functions: 您可以使用窗口函数执行此操作:
select PropertyID, Amount,
sum(Amount) over (partition by PropertyId) as TotalAmount
from yourtable;
The window function for sum()
does the following. sum()
的窗口函数执行以下操作。 It calculates the sum of amount
for groups of rows in the same group. 它计算同一组中的行组的amount
之和。 The group is defined by the partition by
clause, so rows with the same value of PropertyId
are in the same group. 该组由partition by
子句定义,因此具有相同PropertyId
值的行位于同一组中。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.