SQLite 如何对 `GridView` 中列的值求和

SQLite how to sum the values of column in `GridView`

我环顾四周,发现了一些类似的案例,但 none 需要在要汇总的条目中确定具体情况。所以我来了。

我有一个方法 filterPayments returns 我的 PayTable 中的所有条目都基于特定的 GroupID,然后显示在我的 GridView 中。从那里我想对 PayTable 中 5 列中的 2 列的值求和,特别是我的 InterestDue 列。我不确定如何在查询中执行此操作,更不用说仅针对特定列执行此操作了。

问题

如何添加特定列中所有条目的值。

是否可以在 SQLite 查询中执行此操作? 如果是如何使用 filterPayments 的返回值并仅对特定列执行求和? 如果不是那我该怎么做呢?

下面是我的代码片段。

filterPayments

Cursor filterPayments(String Payment) {
    SQLiteDatabase db = this.getWritableDatabase();
    String[] columns = new String[]{"_id", colGroupID, colPayBal, colInterest, colDue, colDateDue, colPaid};
    Cursor c = db.query(viewPmnts, columns, colGroupID + "=?", new String[]{Payment}, null, null, null);
    return c;
}

GridView

public void Paygrid() {

    dbHelper = new DatabaseHelper(this);
    String Payment = String.valueOf(txt.getText());
    Cursor a = dbHelper.filterPayments(Payment);
    startManagingCursor(a);

    String[] from = new String[]{DatabaseHelper.colPayBal, DatabaseHelper.colInterest, DatabaseHelper.colDue, DatabaseHelper.colDateDue, DatabaseHelper.colPaid};
    int[] to = new int[]{R.id.Amount, R.id.Interest, R.id.Due, R.id.DateDue, R.id.Paid};

    SimpleCursorAdapter saa = new SimpleCursorAdapter(this, R.layout.paygrid, a, from, to);
    intgrid.setAdapter(saa);
}

我建议从列中提取所有数据,然后将它们汇总到 Java 或 android 中。那将是最简单的方法。

没有执行此操作的核心 sqlite 函数。 https://www.sqlite.org/lang_corefunc.html

但是您可以创建自定义 sqlite 函数。往下看。 How to create custom functions in SQLite

希望我能正确回答您的问题。但是,如果您有两列,列名分别为 interestdue,则可以使用 SQL 查询

获取两列的总和
SELECT interest + due FROM PayTable;

这也适用于乘法(及其逆运算)。不幸的是,它对于非整数求幂(如平方根)变得更加棘手。据我所知,您需要已经提到的自己的 SQLite 函数。如果幸运的话,您可以从 C 标准库中加载一个包含 math.h 的模块(搜索 extension-functions.c

有关表格中其他求和方式,请参阅 this question for PostgreSQL(SQLite 也相同)