2016-08-12 57 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