[英]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" 但它不起作用,它返回0,并且附带警告说没有名为“ hours”的列
I think most database engines would name the column in the result of your query after the outermost aggregate function -- SUM
. 我认为大多数数据库引擎都会在最外层的汇总函数SUM
之后命名查询结果中的列。
Try changing your query to SELECT SUM(hours) AS hours FROM inputs
. 尝试将查询更改为SELECT SUM(hours) AS hours FROM inputs
。 (Or, if you're querying Oracle, you unlucky person, the query is without the AS
.) (或者,如果您要查询Oracle,那么您很不幸,查询将不包含AS
。)
The following code will work: 以下代码将起作用:
-(NSInteger)calculateTotal
{
FMDatabase *dbHandler = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
if(![dbHander open])
{
NSLog(@"Could not open DB, try again");
return -1; //return some value that tells you that there was an error
}
FMResultSet *results = [dbHandler executeQuery:@"SELECT SUM(hours) AS sum_hours FROM inputs"];
NSInteger totalHours = -1;
while ([results next]) {
totalHours = [results intForColumn:@"sum_hours"];
}
[results close];
[dbHandler close];
return totalHours;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.