如何在游标查询中使用group by子句?

时间:2015-04-20 05:39:12

标签: android sqlite

我想在以下游标查询中使用“helper.TX_NAME”列上的group by子句提出合并报告。

String[] columns = {VivzHelper.UID, helper.TX_NAME, helper.TX_PARTICULARS, helper.TX_AMOUNT, helper.TX_DATE};

Cursor c = db.query(VivzHelper.TX_TABLE, 
    columns, 
    helper.TX_ID + "='" + name + "' AND " + helper.TX_DATE + " BETWEEN '" + datefrom.from_date + "' AND '"  + dateto.to_date + "  ' ", 
    null, 
    null, 
    null, 
    null, 
    null);

2 个答案:

答案 0 :(得分:1)

要获取每个日期和名称组合的输出行,请按以下列分组:

SELECT Date,
       Name,
       SUM(Amount) AS Amount
FROM TxTable
GROUP BY Date,
         Name

在Java中,只需将各个部分放入适当的参数中:

String[] columns = {
    helper.TX_NAME,
    "SUM("+helper.TX_AMOUNT+") AS "+helper.TX_AMOUNT,
    helper.TX_DATE
};
db.query(VivzHelper.TX_TABLE,
         columns,
         helper.TX_ID + "= ? AND " + helper.TX_DATE + " BETWEEN ? AND ?",
         new String[] { name, datefrom.from_date, dateto.to_date },
         helper.TX_NAME + ", " + helper.TX_DATE,
         null, null);

答案 1 :(得分:0)

你可以试试这个:

Cursor c1 = database.rawQuery("SELECT * FROM " + VivzHelper.TX_TABLE+ " where '"+ helper.TX_ID + "'='" + name + "' AND " + helper.TX_DATE + " BETWEEN '" + datefrom.from_date + "' AND '"  + dateto.to_date + "' GROUP BY "+helper.TX_NAME, null);

注意:您可以使用列名而不是" *"在SELECT Query中。

Cursor c = db.rawQuery("SELECT "+ helper.TX_NAME+","+ helper.TX_PARTICULARS+","+ helper.TX_AMOUNT+","+ helper.TX_DATE +" FROM " + VivzHelper.TX_TABLE+ " where '"+ helper.TX_ID + "'='" + name + "' AND " + helper.TX_DATE + " BETWEEN '" + datefrom.from_date + "' AND '" + dateto.to_date + "' GROUP BY "+helper.TX_NAME, null);