2016-08-12 78 views
-1

我有如下表SUM与PARTITION SQL服务器BY子句

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的查询与下面的逻辑,

  • 分组是QuotationId + QuotationDetailId。
  • 对于每个这种块我需要从第二行总结上一行的值固定

    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 

我试过几个查询但没有成功,有人可以建议我一种方法来做到这一点?

问候 法布里奇奥

+1

您能正确格式化数据,以便我们可以读取它吗? –

+1

并告诉我们你已经尝试过,发现不起作用? – dfundako

+4

SQL表格表示*无序*集合。除非列指定了排序,否则没有“上一个”行。什么是排序?结果输出与输入数据完全相同。 –

回答

2

在SQL Server 2012+,你可以做一个累计总和。我不知道确切的逻辑是你想要的,但是这似乎是合理的给出的数据集:

select t.*, 
     sum(FixedAmount*UnitAmount) over (partition by QuotationId, QuotationDetailId 
             order by DriverId 
             ) as running_sum 
from t; 
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