如何获取在CoreData中取平均值的Entity属性

Posted

技术标签:

【中文标题】如何获取在CoreData中取平均值的Entity属性【英文标题】:How to get the Entity property from which an average is taken in CoreData 【发布时间】:2013-07-25 09:27:04 【问题描述】:

我从我的CoreData EntityAveragedGroupedBy date 结果中提取了一些值。查询效果很好。现在...我想知道这些结果的来源dates。显示的输出来自原始结果。我怎么能让我的查询也吐出 date/GroupBy value (given that my GroupBy criteria is date) 从中获取这些平均值

输出

(
        
        averageWeight = 36;
    ,
        
        averageWeight = 22;
    
)

守则:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ExerciseData" inManagedObjectContext:context];
    [request setEntity:entity];

    // Specify that the request should return dictionaries.
    [request setResultType:NSDictionaryResultType];

    // Create an expression for the key path.
    NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"weight"];

    // Create an expression to represent the function you want to apply
    NSExpression *expression = [NSExpression expressionForFunction:@"average:"
                                                         arguments:@[keyPathExpression]];

    // Create an expression description using the minExpression and returning a date.
    NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];

    // The name is the key that will be used in the dictionary for the return value.
    [expressionDescription setName:@"averageWeight"];
    [expressionDescription setExpression:expression];
    [expressionDescription setExpressionResultType:NSInteger32AttributeType]; // For example, NSDateAttributeType

    // Set the request's properties to fetch just the property represented by the expressions.
    [request setPropertiesToFetch:@[expressionDescription]];
    request.predicate = [NSPredicate predicateWithFormat:@"exercise == %@",exercise];
    [request setPropertiesToGroupBy:[NSArray arrayWithObject:@"date"]];
    // Execute the fetch.
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    NSLog(@"%@",objects);

【问题讨论】:

【参考方案1】:

只需添加“日期”作为要获取的另一个属性:

[request setPropertiesToFetch:@[expressionDescription, @"date"]];

【讨论】:

以上是关于如何获取在CoreData中取平均值的Entity属性的主要内容,如果未能解决你的问题,请参考以下文章

如何从数据库数据中取平均值? TypeError: 不支持的操作数类型 /: 'Decimal' 和 'float'

如何根据 R 中的条件对多列取平均值?

R脚本每<x>天取平均值

oracle 取平均值

丢弃异常值后在 SQL 中取平均值

python删除异常值,过滤并取平均值