Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to sum all the columns in a SQLite database and return 1 single variable

My objective is to sum all the columns in my database and return a variable 'total' = x amount.

Example:

column - food | taxi | clothes | sports 
          2       3      4         5
          6       8      0         12
          11      10     7         2

Then therefore the total will equate to = 70

My original idea was to sum individual columns and finally add them together example of summing an individual column:

public Cursor sumFoodColumn(){
    Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, KEY_FOOD + "=?", new String[]{"sum(food)" + KEY_FOOD}, null, null, null, null);
    if (c !=null) {
        c.moveToFirst();
    }
    return c;
}

But I felt this would be a bit laborious as I've got 13 columns in my database, is there a better way around this? Preferably with only 1 query.

like image 688
user3197786 Avatar asked Feb 23 '14 15:02

user3197786


People also ask

How can I sum a column in SQLite in Android?

How can I sum a column in SQLite in Android? Syntax of SQLite SUM() Function Following is the syntax of the SQLite SUM() function to get the sum of values in a defined expression. Expression – Its column or expression which we used to calculate the sum of values in defined column or expression.

How do I sum a column in SQLite?

Using total() it returns 0.0. SQLite sum() function retrieves the sum value of an expression which is made up of more than one columns.

How do you find the sum in SQLite?

The SQLite SUM function is used to return the summed value of an expression. Syntax: SELECT SUM(aggregate_expression) FROM tables.


1 Answers

You can run this query:

Cursor c = db.rawQuery("SELECT Sum(food) + Sum(taxi) + Sum(clothes) + Sum(sports) AS myTotal FROM " + DATABASE_TABLE, null);

Instead of

Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, KEY_FOOD + "=?", new String[]{"sum(food)" + KEY_FOOD}, null, null, null, null);

and get your total as

Cursor c = sumFoodColumn();
int total = c.getInt(c.getColumnIndex("myTotal"));
like image 77
Phantômaxx Avatar answered Sep 29 '22 02:09

Phantômaxx