2013-05-19 63 views
0
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列所產生的平衡?賬戶餘額 - 谷歌電子表格SQL查詢

什麼是最高性能選項?

我知道如何總結和休息價值觀,但我不知道如何把它們乾淨地放在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 - 我,我能得到平衡。但是,我怎樣才能爲通訊元素做到這一點?我的意思是銀行和銀行等。

回答

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)

+0

看上去不錯,將考驗 – juanpastas