我想得到一个列中所有值的总和,以获得不同的id(在我的情况下是日期)。我的代码是
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Table"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(endTime!=%@)",nil];
[fetchRequest setPredicate:predicate];
fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.returnsDistinctResults=YES;
NSExpressionDescription *aDescription = [[NSExpressionDescription alloc] init];
aDescription.name = @"A";
aDescription.expression = [NSExpression expressionForKeyPath:@"@sum.a"];
aDescription.expressionResultType = NSDecimalAttributeType;
NSExpressionDescription *bDescription = [[NSExpressionDescription alloc] init];
bDescription.name = @"B";
bDescription.expression = [NSExpression expressionForKeyPath:@"@sum.b"];
bDescription.expressionResultType = NSDecimalAttributeType;
NSArray *properties = [NSArray arrayWithObjects:@"date",aDescription, bDescription, nil];
[fetchRequest setPropertiesToFetch:properties];
NSArray *result = [temporaryContext executeFetchRequest:fetchRequest error:&error];
NSLog(@"Array result is : %@",result);
当我运行上述查询时,我得到列a,列b和不同日期的总和。问题是它不会将不同日期的总和相加,而是会将a和b列中的所有值相加。
简单来说,我想在这个问题中Link获得结果,但在核心数据中。任何帮助将不胜感激。
答案 0 :(得分:1)
尝试将获取请求设置为分组:
[fetchRequest setPropertiesToGroupBy:@[ @"date" ]];