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

给你一囗甜甜゛ 提交于 2020-01-07 01:23:51

问题


I've had a look around and found a few similar cases but none where there is a need for specificity in the entries to sum. So here I am.

I have a method filterPayments that returns all entries in my PayTable based on a specific GroupID and is then displayed in my GridView. From there I want to sum the values of 2 of the 5 columns in PayTable, specifically my Interest and Due columns. I'm not sure how to do this in a query, let alone do it only for specific columns.

Question

How do I add the values of all entries in a specific column.

Is it possible to do this in a SQLite query? If so how do I use the returned value of filterPayments and perform the summation only on specific columns? If it isn't then how can I do this?

Below are my code snippets.

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

回答1:


I suggest pulling all the data from column and then sum them in Java or android. That would be the simplest way.

There are no core sqlite functions that does it. https://www.sqlite.org/lang_corefunc.html

You can however create custom sqlite functions. Look below. How to create custom functions in SQLite




回答2:


I hope I get your question right. But if you have two columns with the column names interest and due you can get the sum of both columns with the SQL query

SELECT interest + due FROM PayTable;

This also applies for multiplication (and its inverse counterparts). Unfortunately it gets more tricky for non-integer exponentiation (like square root). As far as I know, you need the already mentioned own SQLite function. If you are lucky you can load a module wrapping the math.h from the C standard lib (search for extension-functions.c)

For other ways of summing in tables look at this question for PostgreSQL (It's the same for SQLite)



来源:https://stackoverflow.com/questions/29414170/sqlite-how-to-sum-the-values-of-column-in-gridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!