I want to get the sum of all values in a column for a distinct id(date in my case). My code is
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);
When i run the above query i get sum of column a, column b and distinct dates. The problem is it will not add up the sum for a distinct date, instead it will add up all the values in the column a and b.
In simple words i want to get results as in this question Link but in core data. Any help would be greatly appreciated.
Try setting the fetch request to group:
[fetchRequest setPropertiesToGroupBy:@[ @"date" ]];