【问题标题】:Sum of a column for distinct id using core data使用核心数据的不同 id 列的总和
【发布时间】:2014-02-01 09:44:40
【问题描述】:

我想获取不同 id 列中所有值的总和(在我的情况下为日期)。我的代码是

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Table"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(endTime!=%@)",nil];
    [fetchRequest setPredicate:predicate];
    fetchRequest.resultType = NSDictionaryResultType;
    fetchRequest.returnsDistinctResults=YES;
    NSExpressionDescription *aDescription = [[NSExpressionDescription alloc] init];
    aDescription.name = @"A";
    aDescription.expression = [NSExpression expressionForKeyPath:@"@sum.a"];
    aDescription.expressionResultType = NSDecimalAttributeType;

    NSExpressionDescription *bDescription = [[NSExpressionDescription alloc] init];
    bDescription.name = @"B";
    bDescription.expression = [NSExpression expressionForKeyPath:@"@sum.b"];
    bDescription.expressionResultType = NSDecimalAttributeType;

    NSArray *properties = [NSArray arrayWithObjects:@"date",aDescription, bDescription, nil];
    [fetchRequest setPropertiesToFetch:properties];


    NSArray *result = [temporaryContext executeFetchRequest:fetchRequest error:&error];

    NSLog(@"Array result is : %@",result);

当我运行上述查询时,我得到 a 列、b 列和不同日期的总和。问题是它不会将不同日期的总和相加,而是将 a 和 b 列中的所有值相加。

简而言之,我想在这个问题Link 中得到结果,但在核心数据中。任何帮助将不胜感激。

【问题讨论】:

    标签: ios core-data nspredicate nsexpression


    【解决方案1】:

    尝试将获取请求设置为组:

    [fetchRequest setPropertiesToGroupBy:@[ @"date" ]];
    

    【讨论】:

    • 感谢您的回答。我的错误,简单的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 2017-07-20
    • 2015-02-13
    相关资源
    最近更新 更多