Question

I have an entity Transaction which among others have 2 variables called "ownedAccount" and "amount".

What i would like to do is do get all Transaction's group them by ownedAccount and get the sum of the amounts in each Group

Thank you in advance

Was it helpful?

Solution

You have to create a NSFetchRequest and use the setPropertiesToGroupBy method.

To get the sum of an attribute you have to use a combination of NSExpression and NSExpressionDescription:

NSExpression *amountExpr = [NSExpression expressionForKeyPath:@"amount"];
NSExpression *totalAmountExpr = [NSExpression expressionForFunction:@"sum:" arguments:@[amountExpr]];
NSExpressionDescription *totalAmountExprDesc = [[NSExpressionDescription alloc] init];
[totalAmountExprDesc setName:@"totalAmount"];
[totalAmountExprDesc setExpression: totalAmountExpr];
[totalAmountExprDesc setExpressionResultType:NSDoubleAttributeType];

Further information about NSExpression: Apple Docs NSExpression


When creating the NSFetchRequest you have to make sure to set the result to be NSDictionaryResultType and to add the totalAmountExprDesc to the properties to fetch. Note that you also add the attribute that you want to group by to the properties to fetch.

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"YourEntityName"];
[fetchRequest setResultType:NSDictionaryResultType];
[fetchRequest setPropertiesToFetch:@[@"ownedAccount", totalAmountExprDesc, ...]];
[fetchRequest setPropertiesToGroupBy:@[@"ownedAccount"]];

Further information about NSFetchRequest: Apple Docs NSFetchRequest

With that you have the basic fetch request to use for your query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top