只是进行连接似乎并不能保证顺序,但得出的最终答案是好的:
select
x.STUDENT_NAME
, sum(y.marks) marks
from
SCORE_CHART x
join SCORE_CHART y
on x.STUDENT_NAME <= y.STUDENT_NAME
group by x.STUDENT_NAME
order by x.STUDENT_NAME
只是看起来没有加入规则 - 会重新思考
编辑- 现在运行正常:LIVE FIDDLE HERE
创建数据
CREATE TABLE "SCORE_CHART"
(
"STUDENT_NAME" NVARCHAR(20),
"MARKS" INT
)
INSERT INTO SCORE_CHART (STUDENT_NAME, MARKS)
VALUES
('STUD1', 95),
('STUD2', 90),
('STUD3', 98)
使用递归 CTE:
;WITH
init_cte(row,STUDENT_NAME,MARKS)
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY STUDENT_NAME),
STUDENT_NAME,
MARKS
FROM SCORE_CHART
)
,MinMax_cte(MinRow,MaxRow) AS (SELECT MIN(row),MAX(row) FROM init_cte)
,recursive_cte (row,STUDENT_NAME,MARKS,RUNNING_MARKS) AS
(
SELECT row,STUDENT_NAME,MARKS,MARKS
FROM init_cte
WHERE row = (SELECT MinRow FROM MinMax_cte)
UNION ALL
SELECT Y.row,y.STUDENT_NAME,y.MARKS,x.RUNNING_MARKS + y.MARKS
FROM recursive_cte x
INNER JOIN init_cte y
ON y.row = x.row + 1
WHERE y.row <= (SELECT [MaxRow] from MinMax_cte)
)
SELECT * FROM recursive_cte
正如在对您的评论中提到的,OP 有一个类似的问题HERE ON SO
在那个问题中,Sam Saffron 提出了一种非常优雅的方式来使用UPDATE
. 这适用于您的数据:
使用上面创建的相同数据,但使用 UPDATE 技巧:
CREATE TABLE #t ( ROW int, STUDENT_NAME NVARCHAR(20) , MARKS int, MARKS_RUNNING int)
INSERT INTO #t
SELECT
ROW_NUMBER() OVER (ORDER BY STUDENT_NAME),
STUDENT_NAME,
MARKS,
0
FROM SCORE_CHART
DECLARE @total int
SET @total = 0
UPDATE #t SET marksrunning = @total, @total = @total + MARKS
SELECT * FROM #t