如何在获取内联结果中总结两个字段?

时间:2016-04-21 14:46:17

标签: sql

我有拖曳字段,例如在一张表中记入借记卡。 我需要对它们求和并在每一行得到结果,例如:

date          debit   credit  amount
2015/01/01     20       0        20
2015/01/02      0       5        15
2015/01/03      0       30      -15

我希望你帮助我通过查询获得金额 感谢

2 个答案:

答案 0 :(得分:0)

使用SQL-Server 2012或更新版本,您可以使用:

SELECT [date], debit, credit, amount,
   SUM(debit-credit) OVER(ORDER BY [date] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS amount
FROM TableName
ORDER BY [date]

阅读:OVER-clause,尤其是ROWS | RANGE部分

对于其他版本,您必须使用相关子查询:

SELECT [date], debit, credit, amount,
  (SELECT SUM(debit-credit) 
   FROM TableName t2
   WHERE [date] <= t1.[date]) AS amount
FROM TableName t1
ORDER BY [date]

答案 1 :(得分:0)

我同意蒂姆的回答,我补充了一些额外的界限:

declare @credit as table (
    [date] datetime,
    amount int
)

declare @debit as table (
    [date] datetime,
    amount int
)

insert into @debit values 
    ('2015-01-01', 20)

insert into @credit values 
    ('2015-01-02', 5),
    ('2015-01-03', 30)


select
    [date], debit, credit, SUM(debit-credit) OVER(ORDER BY [date] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS amount
from(
    select 
        [date], sum(debit) debit, sum(credit) credit
    from
    (
    select 
        [date], 0 credit, d.amount debit
    from
        @debit d
    union all
    select 
        [date], c.amount credit, 0 debit
    from
        @credit c
    ) j group by j.date
) x