自参考计算字段

时间:2014-02-28 18:58:09

标签: sql-server sql-server-2012

我有一个表格,其数据类似于:

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

基本上我需要的是第三个字段,它是它之前的所有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语句,但我担心有一些概念方法我完全不知道。

我几乎没有兴趣弄清楚实际的代码,而只是围绕着我将在这里采用的一般概念中的任何概念......

2 个答案:

答案 0 :(得分:0)

试试这个:

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

PS:我不确定你的意思是按层分组,因为你想要的结果按图层和layerPerOccLimit分组......

答案 1 :(得分: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
*/