SQL中的递归函数

时间:2013-11-15 06:29:45

标签: sql function recursion

我的表中的数据如下,

+----+-----+
| ID | Qty |
+----+-----+
|  1 | 100 |
|  2 | 200 |
|  3 | 150 |
|  4 |  50 |
+----+-----+

我需要如下结果,

+----+-----+-------+
| ID | Qty | C.Qty |
+----+-----+-------+
|  1 | 100 |   100 |
|  2 | 200 |   300 |
|  3 | 150 |   450 |
|  4 |  50 |   500 |
+----+-----+-------+

第三列的结果将是前一行的总和, 请任何一个帮助......

4 个答案:

答案 0 :(得分:2)

我只想使用子查询:

SELECT ID, Qty,
   (SELECT SUM(Qty) FROM [My Table] b WHERE b.ID <= [My Table].ID) AS [Total Qty]
FROM [My Table]

答案 1 :(得分:2)

请尝试:

SELECT S1.ID, S1.Qty ,sum(S2.Qty) CUM_SUM
FROM YourTable S1 join YourTable S2
on S1.ID>=S2.ID
group by S1.ID, S1.Qty
ORDER BY S1.ID

答案 2 :(得分:1)

 SELECT ID, Qty,
 SUM(Qty) OVER(ORDER BY ID 
 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) 
      AS C.QTY
 FROM Table

答案 3 :(得分:0)

试试这个:

select a.id,a.qty,sum(b.qty) as total_qty
from table a cross join table b
where b.id <= a.id
group by a.id,a.qty 
order by a.id

demo