核心数据的GROUP BY等效 [英] GROUP BY equivalent for Core Data

查看:97
本文介绍了核心数据的GROUP BY等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that I can use @distinctUnionOfObjects to find something like the following in SQL:

SELECT a_value
FROM my_table
GROUP BY a_value;

我要查找的是数组,而不仅仅是与表达式匹配的值的数组。基本上,我正在寻找相当于以下对核心数据的SQL查询:

What I'm looking for is all of the data returned in an array, not just the array of values that matches the group by expression. Essentially, I'm looking for the equivalent of the following SQL query for core data:

SELECT *
FROM my_table
GROUP BY a_value;


推荐答案

这是模拟

SELECT'Status',COUNT(*)FROM'Records'GROUP BY'Status'

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

在此找到

这篇关于核心数据的GROUP BY等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆