我正在尝试对带有过滤器的窗口求和。我看到类似的东西
sum(x) filter(condition) over (partition by...)
但它似乎在t-sql SQL Server 2017中不起作用。
基本上,我想对在另一列上有条件的最后5行进行求和。
我尝试过
sum(case when condition...) over (partition...)
和sum(cast(nullif(x))) over (partition...)
。
我尝试过使用where条件将表联接到表中,以过滤条件。
以上所有条件将从当前行的起始点开始加上后5个条件。
我想要的是当前行。在上面添加满足条件的最后5个值。
Date| Value | Condition | Result
1-1 10 1
1-2 11 1
1-3 12 1
1-4 13 1
1-5 14 0
1-6 15 1
1-7 16 0
1-8 17 0 sum(15+13+12+11+10)
1-9 18 1 sum(18+15+13+12+11)
1-10 19 1 sum(19+18+15+13+12)
在上面的示例中,我希望的条件是1,忽略0,但“窗口”大小仍然是5个非0值。
答案 0 :(得分:0)
可以使用相关子查询轻松实现:
首先,创建并填充示例表(请在您将来的问题中为我们保存此步骤):
DECLARE @T AS TABLE
(
[Date] Date,
[Value] int,
Condition bit
)
INSERT INTO @T ([Date], [Value], Condition) VALUES
('2019-01-01', 10, 1),
('2019-01-02', 11, 1),
('2019-01-03', 12, 1),
('2019-01-04', 13, 1),
('2019-01-05', 14, 0),
('2019-01-06', 15, 1),
('2019-01-07', 16, 0),
('2019-01-08', 17, 0),
('2019-01-09', 18, 1),
('2019-01-10', 19, 1)
查询:
SELECT [Date], [Value], Condition,
(
SELECT Sum([Value])
FROM
(
SELECT TOP 5 [Value]
FROM @T AS t1
WHERE Condition = 1
AND t1.[Date] <= t0.[Date]
-- If you want the sum to appear starting from a specific date, unremark the next row
--AND t0.[Date] > '2019-01-07'
ORDER BY [Date] DESC
) As t2
HAVING COUNT(*) = 5 -- there are at least 5 rows meeting the condition
) As Result
FROM @T As T0
结果:
Date Value Condition Result
2019-01-01 10 1
2019-01-02 11 1
2019-01-03 12 1
2019-01-04 13 1
2019-01-05 14 0
2019-01-06 15 1 61
2019-01-07 16 0 61
2019-01-08 17 0 61
2019-01-09 18 1 69
2019-01-10 19 1 77