T-sql查询获得应用假的运行差异

时间:2017-10-03 13:08:53

标签: sql sql-server tsql

这是我的表:

enter image description here

我需要在上表中运行应用假的差异。这里申请休假是10,总余额是8。我需要在最后一行显示-2(8-10 = -2)。

我的尝试:

 ;WITH x AS
(
    select abs(balance-(applied))req  from mytest where rno=1 
    UNION ALL
    select abs(mytest.balance-abs(x.req))  from x join  mytest on  mytest.rno=x.rno+1
)
SELECT balance, balance-req
    FROM x

实际结果:

enter image description here

预期结果:

balance |   applied
5.00    |       0
2.00    |       0
1.00    |       -2

任何人都可以帮助解决这个问题??? ...提前感谢....

2 个答案:

答案 0 :(得分:2)

您可以使用SUMOVER结合ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW计算每一行的差异:

DECLARE @DataSource TABLE
(
    [rno] INT
   ,[balance] DECIMAL(9,2)
   ,[applied] DECIMAL(9,2)
);

INSERT INTO @DataSource ([rno], [balance], [applied])
VALUES (1, 5, 10)
      ,(2, 2, 0)
      ,(3, 1, 0);

SELECT [rno]
      ,[balance]
      ,SUM([balance] - [applied]) OVER (ORDER BY [rno] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS [applied]
FROM @DataSource;

enter image description here

如果您知道最后一行的0,则可以使用其他操作或IIFID设置为其余的运行差异(最后一个除外)。< / p>

答案 1 :(得分:1)

您可以使用窗口功能。关键是累积的余额总和:

select t.rno, t.balance, t.applied,
       (case when max_rno = rno then cume_balance - sum_applied
             else 0
        end) as new_applied
from (select t.*,
             sum(balance) over (order by rno) as cume_balance,
             max(rno) over () as max_rno,
             sum(applied) over () as sum_applied
      from mytable t
     ) t;