0

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);
}
Cai
  • 5,063
  • 3
  • 18
  • 23

2 Answers2

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

Community
  • 1
  • 1
  • Alright then, thanks for the clarification on that. I'll just put it in an array and sum it up from there. Cheers! – Cai Apr 02 '15 at 14:04
1

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)

Daniel
  • 141
  • 1
  • 10