需要SQL查询才能获得以下输出。 "付费金额" &安培; "收到的金额"列已经存在于表中。想要产生"投入金额"

时间:2017-06-27 05:10:54

标签: sql-server

|Paid Amount | Received Amount | Invested Amount
| 10000      |    --           |  10000
|   --       |   8000          |   2000
|  5000      |    --           |   7000
|   --       |   4000          |   3000

1 个答案:

答案 0 :(得分:0)

假设您还有一个对事务进行排序的日期列,您可以使用以下相关子查询来查找运行总计:

SELECT
    t1.[Paid Amount],
    t1.[Received Amount],
    (SELECT SUM(COALESCE(t2.[Paid Amount], 0) - t2.[Recieved Amount])
     FROM yourTable t2
     WHERE t2.date <= t1.date) AS [Invested Amount]
FROM yourTable t1
ORDER BY t1.date