表中列的累积拆分因子

时间:2014-02-13 06:58:46

标签: sql sql-server sql-server-2008

我有一张看起来像这样的表:

  A           B
1.2902      5.356
1.2         5.356
1.3         5.356
1.4         5.356
1.2         5.356
1.2         5.356
1.2         5.356
1.1         5.356

我想获得如下的值:

A             B
1.2902      5.356
1.2         4.151294373
1.3         3.193303364
1.4         2.280930974
1.2         1.900775812
1.2         1.583979843
1.2         1.319983203
1.1         1.19998473

解释:

If
A1 = 1.2902    & B1=5.356
A2=1.2      then B2 should be B1/A1 
A3=1.3      then B3 should be B2/A2
A4=1.2      then B4 should be B3/A3
A5=1.2      then B5 should be B4/A4
A6=1.2      then B6 should be B5/A5
A7=1.1      then B7 should be B6/A6

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

如果表中有主键,数据按主键顺序排列(即没有任何丢失的记录),那么可以使用下面的递归CTE来完成

;with CTE as
(
   SELECT  Id,A,B FROM Test t1 WHERE Id = 1

   UNION ALL

   SELECT  t1.Id, t1.A, CAST(CTE.B/CTE.A AS decimal(18,10)) AS B
   FROM Test t1
   INNER JOIN CTE ON t1.Id - 1 = CTE.Id
)

SELECT * FROM CTE

<强> SQL Fiddle Demo