Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLITE SUM and LIMIT don't seem to work together

I'm trying to retrieve the sum of a column from SQLITE. I am able to successfully get it. But when I try to retrieve just the sum of 10 rows, it returns the sum of the entire column again. The query seems to be correct though.

public String getUnitsForWeek(Context context) throws IOException {
    DataBaseHelper dbHelper = new DataBaseHelper(context);

    String query = "SELECT sum(UNITS) FROM SERVICE_TABLE order by id DESC limit 7";
    return String.valueOf(dbHelper.getString(query));

}

The dbHelper.getString method is:

public int getString(String query) {
    String mypath = DB_PATH + DB_NAME;
    SQLiteDatabase database = SQLiteDatabase.openDatabase(mypath, null, 
            SQLiteDatabase.OPEN_READWRITE);
    Cursor cursor = null;

    int i;

    cursor = database.rawQuery(query, null);


    cursor.moveToFirst();
    i= cursor.getInt(cursor.getColumnIndex(cursor.getColumnName(0)));
    return i;

}

Thanks.

like image 707
pixelscreen Avatar asked Dec 15 '25 12:12

pixelscreen


2 Answers

SUM is an aggregate function that combines data from many rows into one. Since there is only one result row, LIMIT and ORDER BY are meaningless.

To sum UNITS on the 7 rows with highest ID, you can use a subselect:

SELECT SUM(UNITS) FROM (SELECT UNITS FROM SERVICE_TABLE ORDER BY id DESC LIMIT 7);
like image 147
laalto Avatar answered Dec 17 '25 01:12

laalto


Can't you do a subelect?

SELECT sum(UNITS) FROM (SELECT UNITS FROM SERVICE_TABLE order by id DESC limit 7) s
like image 39
Pieter B Avatar answered Dec 17 '25 00:12

Pieter B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!