Небольшое изменение в приведенном выше коде на Sean
, в то время как его код добавляет все строки, это исправляет проблему:
CREATE TABLE #t (Symbol varchar(5),Date datetime,Quarter varchar(10),Type varchar(2),Revenue int)
GO
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('A1','12/31/2018','4q2018','x1',5000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('B1','12/31/2018','4q2018','x2',2000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('C1','12/31/2018','4q2018','x3',3500)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('D1','12/31/2018','4q2018','x4',2000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('A1','09/30/2018','3q2018','x1',1000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('B1','09/30/2018','3q2018','x2',2000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('C1','09/30/2018','3q2018','x3',1500)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('D1','09/30/2018','3q2018','x4',2500)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('A1','06/30/2018','2q2018','x1',1000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('B1','06/24/2018','2q2018','x2',4000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('C1','06/30/2018','2q2018','x3',1000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('D1','06/30/2018','2q2018','x4',2000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('A1','03/31/2018','1q2018','x1',1000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('B1','01/28/2018','1q2018','x2',4000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('C1','02/21/2018','1q2018','x3',1000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('D1','03/31/2018','1q2018','x4',2500)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('A1','12/31/2017','4q2017','x1',1000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('B1','12/31/2017','4q2017','x2',2000)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('C1','12/31/2017','4q2017','x3',1500)
INSERT INTO #t (Symbol,Date,Quarter,Type,Revenue) VALUES('D1','12/31/2017','4q2017','x4',2500)
--SELECT * FROM #t WHERE Symbol = 'B1' ORDER BY Date Desc
select Symbol, [Quarter], SUM(Revenue) OVER (PARTITION BY Symbol
ORDER BY [Date]
ROWS 3 PRECEDING) AS total,Date
FROM #t
ORDER BY Date Desc
Вот еще одно обновление для SQL Server 2008:
select a.Symbol, a.[Quarter], x.Rev,a.Date
FROM #t a
CROSS APPLY ( SELECT ISNULL(SUM(re), 0) Rev
FROM ( SELECT TOP(4) b.Revenue re
FROM #t b
WHERE b.Symbol = a.Symbol and Convert(varchar,b.Date,112) <= Convert(varchar,a.Date,112)
ORDER BY b.Date DESC ) v
) x
ORDER BY a.Date Desc
DROP TABLE #t