我有一个名为UserProfile的表,如下所述
我需要不同的位置,计算不同的位置,并计算在user = user1的不同位置的值为0的状态。状态值可以在0 t0 5(数字)
之间所以输出将是
abc 3 2
abd 1 1
,其中 abc 是唯一的位置, 3 是表格中abc的总计数, 2 是位置abc处状态= 0的总计数
答案 0 :(得分:4)
我可以给你一些灵感,因为我认为,这个状态'可能只有0或1.如果那不是真的,那么 - 我想 - 你必须用不同的谓词执行两个单独的提取(一个用于获取指向user1的位置计数,另一个用于用户的状态计数) = user1和status = 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);