我有一张桌子:
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
让我知道如何获得所需的输出...
答案 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