【问题标题】:SQLite how to sum the values of column in `GridView`SQLite如何对`GridView`中列的值求和
【发布时间】:2015-04-02 13:26:58
【问题描述】:

我环顾四周,发现了一些类似的案例,但没有一个需要对条目进行具体总结。所以我来了。

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

问题

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

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

下面是我的代码 sn-ps。

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);
}

【问题讨论】:

    标签: android sqlite gridview


    【解决方案1】:

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

    没有核心的 sqlite 函数可以做到这一点。 https://www.sqlite.org/lang_corefunc.html

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

    【讨论】:

    • 好的,感谢您对此的澄清。我将把它放在一个数组中并从那里总结出来。干杯!
    【解决方案2】:

    我希望我能正确回答您的问题。但是,如果您有两列名称为 interestdue,您可以使用 SQL 查询获得两列的总和

    SELECT interest + due FROM PayTable;
    

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

    对于其他表格求和的方法,请查看this question for PostgreSQL(SQLite 也是如此)

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      相关资源
      最近更新 更多