sum数据库值按第二个表键分组

时间:2013-06-07 17:44:33

标签: javascript sqlite group-by

我有以下表格

条形码独有的billpayments表

barcode    amount    receiptno
123        10        1
124        20        1
125        10        2
126        10        2
127        20        3

具有唯一条形码的帐单表

barcode    buildingcode  
123        1001
124        1001
125        1002
126        1002
127        1002

我想显示按照构建代码分组的金额总和

buildingcode     sum amount
1001             30
1002             40

我使用以下代码,但我只按receiptno分组

t.executeSql('SELECT barcode, SUM(amount) AS myamount, receiptno FROM billpayments WHERE receiptno > 0 GROUP BY receiptno', 
        [], function(t, resultcollect) {

            len = resultcollect.rows.length;

            function dummy(i){
                var row = resultcollect.rows.item(i);
                t.executeSql('SELECT barcode, buildingcode FROM bill WHERE barcode = ?', 
                    [row.barcode], function(t, collectaddress) {
                        mybill = collectaddress.rows.item(0);

                        if (row.receiptno != 0){
                            items.push('<tr><td>' + row.receiptno + '</td><td>' + mybill.buildingcode + '</td><td><font color="blue">' + row.myamount.toFixed(2) + '</font></td><td></td></tr>');
                        }
                    });
            }

            for (i = 0; i < len; i += 1) {
                dummy(i);
            }

我该怎么做?

1 个答案:

答案 0 :(得分:0)

SELECT buildingcode, SUM(amount)
FROM bill JOIN billpayments ON bill.barcode = billpayments.barcode
GROUP BY buildingcode