【问题标题】:Sum of distinct values in core data核心数据中不同值的总和
【发布时间】:2015-09-08 14:41:28
【问题描述】:

我的应用中有一个核心数据模型,其中包含一些不同的日期。每个日期都有一个数量值。现在我想在一个查询中获取每个日期的总和。请注意,日期并不明确,这意味着有多个 2015/01/05 等等。

我是核心数据的新手,并且在这些东西上真的很挣扎。知道如何实现这一点。

【问题讨论】:

  • 你能提供更多关于你的模型的细节吗?有问题的日期是用 NSDate 建模的吗?如果是这样,你会去掉时间信息吗?怎么样?
  • 否数据为字符串格式,由年月值组成,如:201509, 201501
  • stackoverflow.com/questions/20637440/… 类似,并且有更长的代码示例。但它没有@pbasdf 的@sum 表达式。

标签: objective-c core-data


【解决方案1】:

一种方法是使用NSExpression 计算总和,并使用propertiesToGroupBy 将总和范围限制为每个不同的日期。假设您的日期属性称为yearMonth,而您要求和的值称为quantity

NSExpression *sumExp = [NSExpression expressionWithFormat:@"sum:(quantity)"];
NSExpressionDescription *sumED = [[NSExpressionDescription alloc] init];
sumED.name = @"sumOfQuantity";
sumED.expression = sumExp;
sumED.expressionResultType = NSDoubleAttributeType;
NSError *error;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"YourEntityName"];
request.propertiesToFetch = @[@"yearMonth", sumED];
request.propertiesToGroupBy = @[@"yearMonth"];
request.resultType = NSDictionaryResultType;
NSArray *results = [context executeFetchRequest:request error:&error];
NSLog(@"Sums of quantity by year/month are: %@", results);

结果应该是一个字典数组,每个字典都有两个键:“yearMonth”作为日期键,“sumOfQuantity”作为对应总和的键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多