1

我想获得一个不同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 列中的所有值相加。

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

4

1 回答 1

1

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

[fetchRequest setPropertiesToGroupBy:@[ @"date" ]];
于 2014-02-01T10:26:17.440 回答