iphone – 与核心数据等效的GROUP BY

语言: CN / TW / HK

我知道我可以使用@distinctUnionOfObjects在SQL中找到类似下面的内容:

SELECT a_value
FROM my_table
GROUP BY a_value;

我正在寻找的是数组中返回的所有数据,而不仅仅是与表组匹配的值数组.本质上,我正在寻找核心数据的以下SQL查询的等价物:

SELECT *
FROM my_table
GROUP BY a_value;

这是模拟的

选择’状态’,COUNT(*)FROM’记录’GROUP BY’状态’:

NSFetchRequest* fetch = [NSFetchRequest fetchRequestWithEntityName:@"Record"];
NSEntityDescription* entity = [NSEntityDescription entityForName:@"Record"
                                          inManagedObjectContext:myManagedObjectContext];
NSAttributeDescription* statusDesc = [entity.attributesByName objectForKey:@"status"];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath: @"url"]; // Does not really matter
NSExpression *countExpression = [NSExpression expressionForFunction: @"count:"
                                                          arguments: [NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName: @"count"];
[expressionDescription setExpression: countExpression];
[expressionDescription setExpressionResultType: NSInteger32AttributeType];
[fetch setPropertiesToFetch:[NSArray arrayWithObjects:statusDesc, expressionDescription, nil]];
[fetch setPropertiesToGroupBy:[NSArray arrayWithObject:statusDesc]];
[fetch setResultType:NSDictionaryResultType];
NSError* error = nil;
NSArray *results = [myManagedObjectContext executeFetchRequest:fetch
                                                         error:&error];

Found here

翻译自:https://stackoverflow.com/questions/4865686/group-by-equivalent-for-core-data

分享到: