添加先前的行值

时间:2018-03-20 05:50:51

标签: sql sql-server tsql

我希望以下面提到的格式获得余额。余额+余额(第1行)我不确定这是否解释得很好但是添加了前一行平衡值到当前行等等......

declare @tab table(Debit int,Credit int)

insert into @tab
select 1000  ,   NULL
union all   
select 2200   ,  NULL  
union all 
select NULL  ,   3000  
union all 
select 1500  ,   1500   


SELECT Debit, Credit, COALESCE(SUM(Credit), SUM(Debit)) AS Balance
FROM @tab
GROUP BY Debit, Credit

这是我到目前为止所做的。

Debit    Credit     Balance
------------------------------
1000     NULL       1000
2200     NULL       2200
NULL     3000       3000
1500     1500       1500

这就是我正在寻找的东西,但请不要让它过于复杂而无法理解。

Debit    Credit     Balance
------------------------------
1000     NULL       1000
2200     NULL       3200
NULL     3000       6200
1500     1500       7700

4 个答案:

答案 0 :(得分:0)

;WITH cte
AS
(
   SELECT Debit, Credit, CAST(ISNULL(Debit,Credit) AS int) AS Balance 
   FROM Table1 

), cteRanked AS
(
   SELECT Debit, Credit, Balance, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum
   FROM cte
) 
SELECT Debit, Credit,
(
  SELECT SUM(Balance) FROM cteRanked c2 WHERE c2.rownum <= c1.rownum
) AS Balance
FROM cteRanked c1;

输出

Debit   Credit  Balance
1000    (null)  1000
2200    (null)  3200
(null)  3000    6200
1500    1500    7700

查看现场演示

  

http://sqlfiddle.com/#!18/978a4/2

答案 1 :(得分:0)

不需要使用GROUP BY子句只需使用窗口功能

SELECT Debit, Credit, 
            SUM(COALESCE(Credit, Debit)) OVER (ORDER BY <identity col> 
                   ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Balance
FROM @tab

答案 2 :(得分:0)

我建议这样做:

MicrosoftAppPassword

或者,如果您需要管理帐户余额,您可以使用此功能。

DECLARE @tab TABLE(id int, Debit int,Credit int)

INSERT INTO @tab (id, Debit, Credit)
VALUES  (1, 1000, NULL),
        (2, 2200, NULL),
        (3, NULL, 3000), 
        (4, 1500, 1500) 

SELECT  Debit, 
        Credit, 
        SUM(COALESCE(Credit, Debit)) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Balance
FROM @tab

谢谢!

答案 3 :(得分:0)

试试这个:

    declare @tab table(id int ,Debit int,Credit int)

    insert into @tab
    select 1, 1000  ,   NULL
    union all   
    select 2, 2200   ,  NULL  
    union all 
    select 3,NULL  ,   3000  
    union all 
    select 4, 1500  ,   1500   


    SELECT *,
    SUM(ISNULL(Debit,credit)) OVER(order by id ROWS UNBOUNDED  PRECEDING) 
    from @tab