将列值从第一行添加到当前行

时间:2017-06-12 09:44:32

标签: sql-server

假设我们有table A

x   y

1   2
2   3
3   5
4   6
5   9
6   10

写一个总结如下的查询

table b

x   y
1   2
2   5
3   10
4   16
5   25
6   35

不使用循环就可以解决上述问题。

2 个答案:

答案 0 :(得分:2)

使用sum()over()子句

CREATE TABLE #Table1
    ([x] int, [y] int)
;

INSERT INTO #Table1
    ([x], [y])
VALUES
    (1, 2),
    (2, 3),
    (3, 5),
    (4, 6),
    (5, 9),
    (6, 10)
;
;
select x, sum(y) over (order by x) as y from #table1

答案 1 :(得分:0)

Set @count:=0;
Select x,@count:=@count+y from tablename ORDER BY x;

尝试以上查询。

希望这会对你有所帮助。

相关问题