A B C D E F G
date from to amount account
5/5/2013 bank food 200 bank
5/5/2013 work bank 1200 food
5/5/2013 bank rent 400 work
5/5/2013 work bank 1200 rent
如何在F列中获得结果余额?
什么是性能最佳的选项?
我知道和和值的关系,但我不知道如何将它们干净地放在F栏中。
我做到了:
in H1
=QUERY(A1:D99,"select B, sum(D) where D > 0 group by B")
in J1
=QUERY(A1:D99,"select C, sum(D) where D > 0 group by C")
获得:
H I J K
from sum Amount to sum Amount
bank 600 bank 2400
work 2400 food 200
rent 400
现在,如果我休息k - i,我可以得到平衡。但是,我怎样才能为相应的元素做到这一点?我的意思是银行与银行等等。
答案 0 :(得分:1)
如果您已在E2中列出了帐户,则可以在F2中输入此数组公式:
=ArrayFormula(IF(LEN(E2:E);SUMIF(C2:C;E2:E;D2:D)-SUMIF(B2:B;E2:E;D2:D);IFERROR(1/0)))
这可能是本答案中任何替代方案的最佳表现。但是,它依赖于已经填充的帐户名称。
此公式将返回整个表格:
=ArrayFormula(QUERY(IF({1,0};TRANSPOSE(SPLIT(CONCATENATE(FILTER(B2:C;LEN(B2:B);LEN(C2:C))&CHAR(9));CHAR(9)));TRANSPOSE(SPLIT(CONCATENATE((FILTER(D2:D;LEN(B2:B);LEN(C2:C))*{-1,1})&CHAR(9));CHAR(9))));"select Col1, sum(Col2) group by Col1 label Col1 'Account', sum(Col2) 'Balance'";0))
但除了非常难以理解之外,这些类型的“连接然后拆分”公式对于大型数据集来说可能具有非常差的性能。所以我通常更喜欢在这种情况下使用自定义函数:
function accountBalance(fromAccount, toAccount, amount) {
var result = [], output = [['Account', 'Balance']], from, to, value;
for (var i = 0; i < amount.length; i ++) {
from = fromAccount[i][0];
to = toAccount[i][0];
value = amount[i][0];
if (from && to) {
if (!(from in result)) result[from] = 0;
if (!(to in result)) result[to] = 0;
result[from] -= value;
result[to] += value;
}
}
for (var j in result) {
output.push([j, result[j]]);
}
return output;
}
然后在电子表格单元格中,您将调用:
=accountBalance(B2:B;C2:C;D2:D)