我试图弄清楚如何进行一种“消费”查询,其中从另一个INT列(Y)中减去INT值列(X),直到它达到0,然后停止。 DesiredResult和DesiredResultExplanation列仅用于参考正在执行的数学运算。这发生在DESC日期顺序(未来消费回到现在)
我最初的方法是使用窗口功能,但问题是一旦值(Y)达到0,它就需要停止执行运行总计。使用CTE也有类似的问题。
如果更改表格结构会有所帮助,可以这样做。
版本:SQL Server 2014或更高版本
谢谢!
DECLARE @test TABLE
(
ID INT IDENTITY (1,1)
,PeriodDate DATE
,X INT
,Y INT
,DesiredResult INT
,DesiredResultExplanation VARCHAR(100)
)
INSERT INTO @test VALUES ('2017-05-01', 100,0, 100,'Nothing left to subtract. Value is unchanged')
INSERT INTO @test VALUES ('2017-05-08', 200,0, 200,'Nothing left to subtract. Value is unchanged')
INSERT INTO @test VALUES ('2017-05-15', 300,0, 100,'300 - 200 = 100 (Orig -1100 has been consumed)')
INSERT INTO @test VALUES ('2017-05-22', 400,0,-200,'400 - 600 = -200 ')
INSERT INTO @test VALUES ('2017-05-29', 500,-1100,-600, '500 - 1100 = -600')
SELECT *
FROM @test
ORDER BY PeriodDate DESC
答案 0 :(得分:3)
<强> DEMO 强>
WITH cte as (
SELECT *,
SUM(X) OVER (ORDER BY PeriodDate DESC) accumulated
FROM @test
), parameter as (
SELECT 1100 as startY
)
SELECT *,
CASE WHEN accumulated <= startY
THEN accumulated - startY
WHEN LAG(accumulated) OVER (ORDER BY PeriodDate DESC) < startY
THEN accumulated - startY
ELSE X
END as newDesire
FROM cte
CROSS JOIN parameter
ORDER BY PeriodDate DESC;
<强>输出强>
编辑:您可以使用
更改LAG
条件
WHEN accumulated - X < startY