sql - 前一天的期末余额作为今天的期初余额
问题描述
我正在为一家小型电子企业开发数据库应用程序。我需要一个 SQL 查询,它将前一天的期末余额作为当天的期初余额。我有以下数据表
Expensis
ExpenseID Date Expense
1 2019-03-01 2,000
2 2019-03-02 1,000
3 2019-03-03 500
收入
IncomeID Date Income
1 2019-03-01 10,000
2 2019-03-02 13,000
3 2019-03-03 10,000
所需结果
Date Opening Balance Income Expense Closing Balance
2019-03-01 0 10,000 2,000 8,000
2019-03-02 8,000 13,000 1,000 20,000
2019-03-03 20,000 10,000 5,00 29,500
解决方案
可以sum
递归使用聚合函数(不能使用lag
窗口解析函数sql server 2008
)
with Expensis( ExpenseID, Date, Expense ) as
(
select 1, '2019-03-01', 2000 union all
select 2, '2019-03-02', 1000 union all
select 3, '2019-03-03', 500
), Income( IncomeID, Date, Income ) as
(
select 1, '2019-03-01', 10000 union all
select 2, '2019-03-02', 13000 union all
select 3, '2019-03-03', 10000
), t as
(
select i.date,
i.income,
e.expense,
sum(i.income-e.expense) over (order by i.date) as closing_balance
from income i
join expensis e on e.date = i.date
)
select date,
( closing_balance - income + expense ) as opening_balance,
income, expense, closing_balance
from t;
date opening balance income expense closing balance
---------- --------------- ------ ------- ---------------
2019-03-01 0 10000 2000 8000
2019-03-02 8000 13000 1000 20000
2019-03-03 20000 10000 500 29500
推荐阅读
- date - 在 Kotlin 中计算日期
- go - 如何编写漂亮干净的 Go 包?
- three.js - 对特定对象应用后处理步骤
- android - Firebase 实时数据库 onChildChanged 在子元素中
- internet-explorer - 使用 VDI 和 Citrix 时有没有办法获取 IE 对象?
- kubernetes - 通过 Istio Gateway/VirtualService 公开开源 Helm 图表
- python - Python pandas - 向数据框中添加多列,其中行和列相互依赖
- jmeter - 如何在jmeter中触发德鲁伊查询
- python-3.x - 在具有另一个数据帧的值的数据帧中应用逐行函数
- woocommerce - 将自定义 javascript 添加到 Woocommerce 编辑产品页面