Search code examples
objective-cxcodefmdbnsinteger

sqlite sum() into nsinteger


I want to build a function which takes the sum of all rows in a column called hours. it should then return an integer value, which i am going to use to multiply with another number.

-(NSInteger)calculateTotal{

FMDatabase *dbHandler = [FMDatabase databaseWithPath:[Utility getDatabasePath]];

[dbHander open];

FMResultSet *results = [dbHandler executeQuery:@"SELECT SUM(hours) FROM inputs"];

NSInteger totalHours;
while ([results next]) {
    totalHours = [results intForColumn:@"hours"];
}

return totalHours;
}

but it doesnt work, it return 0, and it comes with a warning saying no column called "hours"


Solution

  • I think most database engines would name the column in the result of your query after the outermost aggregate function -- SUM.

    Try changing your query to SELECT SUM(hours) AS hours FROM inputs. (Or, if you're querying Oracle, you unlucky person, the query is without the AS.)