1

I have a core data entity that has a created_at attribute which is a NSDate, and an amount attribute which is a NSInteger.

I would like to make a request that returns the sum of amounts grouped by months. Something like:

[['February 2010', 450], ['January 2010', 300]]

I'm not sure how to approach this, if I would have to first fetch all results for a specific date range, and then calculate sum, or if there are other methods.

P.S. I'm doing this on the iphone 4.2 sdk.

Oscar Del Ben
  • 4,485
  • 1
  • 27
  • 41
  • Possible duplicate of [GROUP BY with SUM() using Core Data](https://stackoverflow.com/questions/12637611/group-by-with-sum-using-core-data) – QED Jul 16 '17 at 22:10

2 Answers2

2

Even thought an answer has already be accepted let me add this more sophisticated and faster method for completeness.

Assuming the months aren't modeled in your data model, you will need to fetch the objects in each month and then sum the amounts. Repeat for as many months as you need.

So, the first step is to create a variable predicate for the fetch. Something like this:

NSPredicate *exPred=[NSPredicate predicateWithFormat:@"%@<=created_at<=%@", monthStartDate,monthEndDate];

NSPredicate *exPred=[NSPredicate predicateWithFormat:@"(%@<=created_at) AND (created_at<=%@)", monthStartDate,monthEndDate];

... then execute the fetch and sum the return:

NSNumber *theSum=[@sum.[context executeFetchRequest:theFetch error:&error].amount];

... or less cowboy:

NSArray *fetchedObjects=[context executeFetchRequest:theFetch error:&error];
    // if no error
    NSNumber *theSum=[fetchedObjects valueForKeyPath:@"@sum.amount"];

Put that in a loop for each month.

Predicates and collection operates are much faster than loops. Use them instead of loops whenever possible.

TechZen
  • 64,370
  • 15
  • 118
  • 145
  • I'm sure you're aware that your code is completely incorrect and won't compile. Also, your `NSPredicate` won't parse and will throw an exception. – Dave DeLong Feb 25 '11 at 17:51
  • Thank you, I'm going to try your approach. – Oscar Del Ben Feb 25 '11 at 23:22
  • I ended up using your approach for calculating the sum, while still calculating the first and last date manually as recommended in the accepted answer. – Oscar Del Ben Feb 27 '11 at 18:50
  • Hi, where did you get the `monthStartDate` and `monthEndDate`? I have the same problem here http://stackoverflow.com/questions/42522546/core-data-group-by-monthly-and-sum , but still clueless. Thank you! – Sonic Master Mar 02 '17 at 02:20
0

I'd fetch the range of objects you're interested into an array, then enumerate through that array and add all the amounts up on the go.

I'm not sure if this could be solved by creating a sophisticated request too, but my gut feeling tells me it would be tricky to set up anyway (if possible at all)...

Toastor
  • 8,980
  • 4
  • 50
  • 82