【问题标题】:Account balance - Google Spreadsheet SQL Query帐户余额 - Google 电子表格 SQL 查询
【发布时间】:2013-05-19 04:54:44
【问题描述】:
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 列中的结果余额?

什么是性能最高的选项?

我知道 sum 和 rest 值如何,但我不知道如何将它们干净地放在 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,我可以得到平衡。但是,我怎样才能为对应的元素做到这一点?我的意思是银行与银行等等。

【问题讨论】:

    标签: sql google-sheets accounting


    【解决方案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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多