我有下表
QuotationId QuotationDetailId DriverId RangeFrom RangeTo FixedAmount UnitAmount
-------------------------------------------------------------------------------------------
10579 7 1 1 1 1154.00 0.00
10579 7 2 2 2 1731.00 0.00
10579 11 1 0 10 0.00 88.53
10579 11 2 11 24 885.30 100.50
10579 11 3 25 34 2292.30 88.53
我需要在SQL Server中使用以下逻辑编写查询,
对于这个块中的每个块,我需要从第二行求和上一行的值为
Amount + UnitAmount * RangeFrom + FixedAmount of the current row
所以在这种情况下,结果输出应该是
QuotationId QuotationDetailId DriverId RangeFrom RangeTo FixedAmount UnitAmount
10579 7 1 1 1 1154.00 0.00
10579 7 2 2 2 2885.00 0.00
10579 11 1 0 10 0.00 88.53
10579 11 2 11 24 1770.60 100.50
10579 11 3 25 34 7174.90 88.53
我已经尝试过多次查询但没有成功,有人可以建议我这样做吗?
祝你好运 的Fabrizio
答案 0 :(得分:2)
在SQL Server 2012+中,您可以执行累积总和。我不确定你想要的逻辑是什么,但鉴于数据集,这似乎是合理的:
select t.*,
sum(FixedAmount*UnitAmount) over (partition by QuotationId, QuotationDetailId
order by DriverId
) as running_sum
from t;
答案 1 :(得分:0)
您可以使用子查询,您的“金额”列会在列表列表中显示为括号中的查询,
SELECT ...fields...,
(SELECT SUM(A.unitAmount * A.RangeFrom + A.fixedAmount)
From YourTable A
WHERE A.QuotationId = B.QuotationId
AND A.QuotationDetailId = B.QuotationDetailId
AND A.DriverId <= B.DriverId) AS Amount
From YourTable B