使用其中一种方式:
CREATE TABLE [dbo].[T1]
(
[dt] [int] IDENTITY(1, 1)
NOT NULL ,
qnt [int] NULL ,
CONSTRAINT [PK_T1] PRIMARY KEY CLUSTERED ( [dt] ASC )
WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
)
ON [PRIMARY]
GO
INSERT INTO dbo.T1 ( qnt ) VALUES ( 10 )
INSERT INTO dbo.T1 ( qnt ) VALUES ( -2 )
INSERT INTO dbo.T1 ( qnt ) VALUES ( -4 )
INSERT INTO dbo.T1 ( qnt ) VALUES ( 3 )
INSERT INTO dbo.T1 ( qnt ) VALUES ( -1 )
INSERT INTO dbo.T1 ( qnt ) VALUES ( 5 )
GO
SELECT * ,
RunningSum = T1.qnt + COALESCE(( SELECT SUM(qnt)
FROM T1 AS T1Sub
WHERE ( T1Sub.dt < T1.dt )
), 0)
FROM T1
Go
SELECT T1.dt ,
T1.qnt ,
SUM(T1Inner.qnt)
FROM T1
INNER JOIN T1 AS T1Inner ON ( T1.dt >= T1Inner.dt )
GROUP BY T1.dt ,
T1.qnt
ORDER BY T1.dt ,
T1.qnt
GO
SELECT T1.* ,
T2.RunningSum
FROM T1
CROSS APPLY ( SELECT SUM(qnt) AS RunningSum
FROM T1 AS CAT1
WHERE ( CAT1.dt <= T1.dt )
) AS T2
Go
SELECT * ,
RunningSum = ( SELECT SUM(qnt)
FROM T1 AS T1In
WHERE ( T1In.dt <= T1.dt )
)
FROM T1
Go
-- In Sql Server 2012
SELECT * ,
SUM(T1.qnt) OVER ( ORDER BY T1.dt
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW )
AS RunningTotal
FROM T1
Drop Table [dbo].[T1]