有没有办法GROUP BY
基于当时月份的核心数据SUM
它的属性?
我有这样的数据
------------------------
date | amount
------------------------
30-08-2017 | 124000000
28-10-2017 | 124000000
16-10-2017 | 124000000
14-12-2017 | 124000000
20-12-2017 | 124000000
------------------------
我只需要显示最近的一年,所以我创建了这样的获取请求
NSDate *now = [NSDate date];
NSDate *oneYearAgo = [now addYears:-1];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyTable" inManagedObjectContext:moc];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(myDate >= %@) AND (myDate <= %@) AND isActive == %@", oneYearAgo, now, @YES];
[request setPredicate:predicate];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"myDate" ascending:YES];
[request setSortDescriptors:@[sort]];
NSExpressionDescription* ex = [[NSExpressionDescription alloc] init];
[ex setName:@"totalCost"];
[ex setExpression:[NSExpression expressionWithFormat:@"@sum.amount"]];
[ex setExpressionResultType:NSDecimalAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObjects:@"myDate", ex, nil]];
[request setPropertiesToGroupBy:[NSArray arrayWithObject:@"myDate"]];
[request setResultType:NSDictionaryResultType ];
NSArray *result = [moc executeFetchRequest:request error:nil];
这是我需要的最接近的解决方案,但是该分组仍然基于日期但月份,并且它并没有总结它的数量。
所以我想得到这样的结果
Aug 2017 | 124000000
Oct 2017 | 248000000
Dec 2017 | 248000000
任何帮助,将不胜感激。谢谢!
最佳答案
您可以使用带有自定义部分路径的 NSFetchResultsContoller 根据月份对数据进行分组。然后,您可以对该部分中的所有项目求和以获得所需的结果。以下代码片段可用于创建获取结果 Controller
NSFetchedResultsController *dateAmountFetchResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:@"monthIndex" cacheName:@"MyEntity"];
在您的 DateAmount 实体上创建一个新的临时属性,称为“monthIndex”。然后在 DateAmount 类 -(NSString*)monthIndex 上创建一个方法,以返回正确的月份数字字符串。根据上面的代码片段,@"monthIndex"应该用作您获取的结果 Controller 的部分名称键路径。
在获取请求的排序描述符中,使用带有键 @"monthIndex"的排序描述符对项目进行排序,因为这是 NSFetchedResultsController 的要求。
关于ios - 核心数据按月和总和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42522546/