let
HJ = Excel.CurrentWorkbook(){[Name="表2"]}[Content],
MX = Excel.CurrentWorkbook(){[Name="表1"]}[Content],
Custom1 = Table.Group(MX,"ld",{"n",each List.Accumulate(List.Sort([明细],1),{},(x,y)=>x&{List.Min({Table.SelectRows(HJ,(h)=>h[ld]=[ld]{0})[合计]{0}-List.Sum(x),y})})}),
"Expanded {0}" = Table.ExpandListColumn(Custom1, "n")
in
"Expanded {0}"