2014-02-28 116 views
-1

我有類似這樣的數據表:自引用計算字段

Layer | LayerPerOccLimit 
    1    40    
    2    60    
    3    75 
    4    96 
    5    102 

基本上我需要的是第三場,這將是在所有preceed它LayerPerOccLimits的總和。所以,我們的目標是在總結柱:

Layer | LayerPerOccLimit | *Aggregate* 
    1   40    0 
    1   80    0 
    2   60    120 
    3   75    180 
    3   25    180 
    4   96    280 
    4   10    280 
    5   102    386 

編輯。像一個正在運行的總數,但必須按層列分組。

我已經嘗試過各種方法,例如插入主鍵,然後基於less than表達式的組合構造一個case語句,但我擔心有一些概念方法完全缺失。

我是不是僅僅包裹我的頭周圍的任何概念,我將在這裏使用在一般意義上搞清楚實際的代碼幾乎不感興趣......

+0

You cn查看SQL Server中的運行示例: http://stackoverflow.com/questions/860966/calculate-a-running-total-in-sqlserver – jle

+0

我看到你要去哪裏埠我需要按層列分組。道歉。我的原始數據不夠準確 – StyleCleveland

回答

0

試試這個:

SELECT Layer, LayerPerOccLimit, 
    SUM(LayerPerOccLimit) OVER(ORDER BY Layer 
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) 
      AS RunningTotal 
    FROM YourTable 

PS :我不太清楚你的意思是按層分組,因爲你想要的結果是由圖層和layerPerOccLimit分組的...

0
DECLARE @MyTable TABLE (
    LayerID   INT NOT NULL, 
    LayerPerOccLimit INT NOT NULL 
); 
INSERT @MyTable (LayerID, LayerPerOccLimit) 
VALUES (1, 40), (1, 80), (2, 60), (3, 75), (3, 100); 

SELECT x.LayerID, 
     SUM(SUM(x.LayerPerOccLimit)) OVER(ORDER BY x.LayerID) - SUM(x.LayerPerOccLimit) AS LayerPerOccLimit_RunningTotals 
FROM @MyTable x 
GROUP BY x.LayerID; 
/* 
LayerID LayerPerOccLimit_RunningTotals 
------- ------------------------------ 
1  0 
2  120 
3  180 
*/ 

SELECT x.LayerID, x.LayerPerOccLimit, rt.LayerPerOccLimit_RunningTotals 
FROM @MyTable x 
INNER JOIN (
    SELECT x.LayerID, 
     SUM(SUM(x.LayerPerOccLimit)) OVER(ORDER BY x.LayerID) - SUM(x.LayerPerOccLimit) AS LayerPerOccLimit_RunningTotals 
    FROM @MyTable x 
    GROUP BY x.LayerID 
) rt -- Running totals 
ON x.LayerID = rt.LayerID; 
/* 
LayerID LayerPerOccLimit LayerPerOccLimit_RunningTotals 
------- ---------------- ------------------------------ 
1  40    0 
1  80    0 
2  60    120 
3  75    180 
3  100    180 
*/ 
+0

我看到你要去哪裏... – StyleCleveland