gpt4 book ai didi

sql - 如何一次选择并导出 5,000 行借记和贷记交易,并使借记和贷记余额为零?

转载 作者:行者123 更新时间:2023-12-01 10:19:38 28 4
gpt4 key购买 nike

我们要迁移到的 ERP 系统需要 GL 行数不超过 5,000 的 csv 文件。每个文件中的借方和贷方交易必须平衡为零。有多个借方和贷方交易行共享一个公共(public)交易 ID。

使用 offset 和 fetch next 我已经能够一次提取 5000 行,但是贷方和借方不平衡。

数据示例:

TranID  Credit  Debit   Balance Account#
1 250 0 250 ABC
1 0 250 0 DEF
2 0 100 -100 GHI
2 50 0 -50 JKL
2 50 0 0 MNO


declare @batchsize INT = 5000,
@loopcount INT = 0;

while (@loopcount*@batchsize < (select count(*) from [Apps2].[dbo].[GLTrans]))
begin
SELECT * FROM [Apps2].[dbo].[GLTrans]
ORDER BY tranID
offset (@batchsize * @loopcount) rows
fetch next (@batchsize) rows only

set @loopcount= @loopcount + 1
end

最佳答案

一个简单的解决方案是预处理所有交易并分配一个批号(针对每个 CSV 文件)。临时表存储每个 TranID 的行数。

假定每个 TranID 的借方和贷方将平衡。

之后,您可以根据临时表生成 CSV。

-- create the temp table
create table #trans
(
TranID int identity,
Cnt int,
Batch int
)

-- populate the temp table
insert into #trans (TranID, Cnt)
select TranID, Cnt = count(*)
from [Apps2].[dbo].[GLTrans]
group by TranID

declare @batchsize int = 5000,
@batch int = 1

while exists (select * from #trans where Batch is null)
begin
update t
set Batch = @batch
from
(
select *, cumm = sum(Cnt) over (order by TranID)
from #trans
where Batch is null
) t
where cumm <= @batchsize

select @batch = @batch + 1
end

-- Verify
select *, sum(Cnt) over (partition by Batch order by TranID)
from #trans
order by TranID

关于sql - 如何一次选择并导出 5,000 行借记和贷记交易,并使借记和贷记余额为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54757321/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com