문제

I want to get the sum of all values in a column for a distinct id(date in my case). My code is

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);

When i run the above query i get sum of column a, column b and distinct dates. The problem is it will not add up the sum for a distinct date, instead it will add up all the values in the column a and b.

In simple words i want to get results as in this question Link but in core data. Any help would be greatly appreciated.

도움이 되었습니까?

해결책

Try setting the fetch request to group:

[fetchRequest setPropertiesToGroupBy:@[ @"date" ]];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top