1

我有一个名为 UserProfile 的表,如下所述

在此处输入图像描述

我需要不同的位置,不同位置的计数和用户 = user1 在不同位置的值为 0 的状态计数。状态值可以在 0 t0 5(number) 之间

所以输出将是

abc 3 2
abd 1 1

其中 abc是唯一位置,3是表中 abc 的总计数,2是位置 abc 的状态 = 0 的总计数

4

1 回答 1

4

我可以给你一些灵感,因为我假设“状态”只能是 0 或 1。如果这不是真的,那么 - 我认为 - 你必须执行两个具有不同谓词的分离提取(一个用于提取计数引用用户 1 的位置和另一个用户 = 用户 1 和状态 = 1 的状态计数。

NSFetchRequest *fetchRequest =  [[NSFetchRequest alloc] init];

//create entity
NSEntityDescription *entity = [NSEntityDescription entityForName:@"UserProfile" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

//filter for user = user1
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"user == %@",user1];
[fetchRequest setPredicate:predicate];

//count of the status == 1 
NSExpressionDescription* sumStatusIsOne = [[NSExpressionDescription alloc] init];
[sumStatusIsOne setExpression:[NSExpression expressionForFunction:@"sum:"
                                            arguments:[NSArray arrayWithObject:[NSExpression expressionForKeyPath:@"status"]]]];
[sumStatusIsOne setExpressionResultType:NSDecimalAttributeType];
[sumStatusIsOne setName:@"sumStatusIsOne"];

//count of the location
NSExpressionDescription* locationCount = [[NSExpressionDescription alloc] init];
[locationCount setExpression:[NSExpression expressionForFunction:@"count:"
                                                 arguments:[NSArray arrayWithObject:[NSExpression expressionForKeyPath:@"Location"]]]
 ];
[locationCount setExpressionResultType:NSDecimalAttributeType];
[locationCount setName:@"locationCount"];

NSArray *subtractComponents = [NSArray arrayWithObjects:
                          locationCount.expression,
                          sumStatusIsOne.expression, nil];

//Count of zero status !!!Important, it is working if the 'status' can be only 1 or 0!!!
NSExpression *countOfZeroStatusExpression = [NSExpression expressionForFunction:@"from:subtract:" arguments:subtractComponents];
NSExpressionDescription* countOfZeroStatus = [[NSExpressionDescription alloc] init];
[countOfZeroStatus setExpression:countOfZeroStatusExpression];
[countOfZeroStatus setExpressionResultType:NSDecimalAttributeType];
[countOfZeroStatus setName:@"countOfZeroStatusExpression"];

[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"Location", locationCount,countOfZeroStatus, nil]];
[fetchRequest setPropertiesToGroupBy:[NSArray arrayWithObject:@"Location"]];
[fetchRequest setResultType:NSDictionaryResultType ];

NSError *error;
NSArray *grouppedResults = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

NSLog(grouppedResults);
于 2014-12-16T10:52:59.857 回答