我们可以在sql server中使用lag函数实现以上功能吗?
我有cust,date,credit amount,debit amount在表中,我需要的cust,date,credit amount,debit amount,closing balance(逻辑是以前的期末余额-当前行借记+目前的信用额度)
我正在尝试
select
*,
LAG (closing balance,1) OVER (Partition by cust ORDER BY cust,date) - Debit + Credit
from table_name
order by cust
我认为您不需要LAG(),只需打开窗口即可SUM():
CREATE TABLE Data (
cust int,
[date] date,
[credit amount] numeric(10, 2),
[debit amount] numeric(10, 2)
)
INSERT INTO Data
(cust, [date], [credit amount], [debit amount])
VALUES
(1, '20200101', 5000.00, 0.00),
(2, '20200101', 0.00, 2000.00),
(2, '20200107', 4000.00, 0.00),
(1, '20200107', 0.00, 2000),
(1, '20200109', 5000.00, 0.00)
声明:
SELECT
cust, [date], [credit amount], [debit amount],
SUM(-[debit amount] + [credit amount]) OVER (PARTITION BY cust ORDER BY [date]) AS [closing balance]
FROM Data
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。