0

我的表中的数据如下,

+----+-----+
| 身份证 | 数量 |
+----+-----+
| 1 | 100 |
| 2 | 200 |
| 3 | 150 |
| 4 | 50 |
+----+-----+

我需要如下结果,

+----+-----+--------+
| 身份证 | 数量 | C.数量 |
+----+-----+--------+
| 1 | 100 | 100 |
| 2 | 200 | 300 |
| 3 | 150 | 450 |
| 4 | 50 | 500 |
+----+-----+--------+

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

4

4 回答 4

2

我只会使用一个子查询:

SELECT ID, Qty,
   (SELECT SUM(Qty) FROM [My Table] b WHERE b.ID <= [My Table].ID) AS [Total Qty]
FROM [My Table]
于 2013-11-15T06:34:16.007 回答
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
于 2013-11-15T06:34:26.687 回答
1
 SELECT ID, Qty,
 SUM(Qty) OVER(ORDER BY ID 
 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) 
      AS C.QTY
 FROM Table
于 2013-11-15T06:34:59.953 回答
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

演示

于 2013-11-15T06:47:19.407 回答