核心数据中的SELECT COUNT(DISTINCT ZUSER)

时间:2015-02-28 11:36:02

标签: ios xcode sqlite ipad core-data

我是核心数据的新手我转换我的sql查询以获取coredata结果但无法转换此查询。

SELECT COUNT (DISTINCT ZUSER) AS Users,ZHOUR ,SUM ( ZLIKE) As Likes FROM ZUSERLIKE where ZDAY=28 AND ZMONTH=2 AND ZYEAR=2015 GROUP BY ZHOUR

任何专家都可以帮助我解决我在这一点面对COUNT(DISTINCT ZUSER)的问题。

1 个答案:

答案 0 :(得分:0)

您需要使用NSExpressionNSExpressionDescription,这些内容如下:

编辑按小组获取COUNT(DISTINCT ZUSER)

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"UserLike"];
// count(ZUSER) NO LONGER REQUIRED:
// NSExpression *userExp = [NSExpression expressionForKeyPath:@"user"];
// NSExpression *countUserExp = [NSExpression expressionForFunction:@"count:" arguments:@[userExp]];
// NSExpressionDescription *countUserED = [[NSExpressionDescription alloc] init];
// countUserED.name = @"Users";
// countUserED.expression = countUserExp;
// countUserED.expressionResultType = NSInteger64AttributeType;

// sum(ZLIKES):
NSExpression *likesExp = [NSExpression expressionForKeyPath:@"likes"];
NSExpression *sumLikesExp = [NSExpression expressionForFunction:@"sum:" arguments:@[likesExp]];
NSExpressionDescription *sumLikesED = [[NSExpressionDescription alloc] init];
sumLikesED.name = @"Likes";
sumLikesED.expression = sumLikesExp;
sumLikesED.expressionResultType = NSInteger64AttributeType;
// set properties to fetch (REPLACED countUserED with @"user"):
request.propertiesToFetch = @[@"user", @"hour", sumLikesED];
// group by hour AND user
request.propertiesToGroupBy = @[@"hour", @"user"];
// filter using predicate...
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"day == %@ AND month == %@ AND year == %@",@28, @2, @2015];
request.predicate = predicate;
// set result type to dictionary (must do for group by to work)
request.resultType = NSDictionaryResultType;
// and execute the query...
NSError *error = nil;
NSArray *interimResults = [context executeFetchRequest:request error:&error];
// Now need to re-aggregate this by hour:
// First build a predicate with substitution variable:
NSPredicate *filter = [NSPredicate predicateWithFormat:@"hour == $HOUR"];
// Create an array to hold the finalResults
NSMutableArray *finalResults = [NSMutableArray arrayWithCapacity:24];
for (int hour = 0; hour < 24; hour++) {
    NSArray *filteredResults = [interimResults filteredArrayUsingPredicate:[filter predicateWithSubstitutionVariables:@{@"HOUR" : [NSNumber numberWithInt:hour]}]];
    NSDictionary *aggregatedResults = @{@"Users" : [filteredResults valueForKeyPath:@"@count"],
                                        @"hour" : @(hour),
                                        @"Likes" : [filteredResults valueForKeyPath:@"@sum.Likes"]};
    [finalResults addObject:aggregatedResults];
}

NSLog(@"finalResults is %@", finalResults);

(我已经根据您问题中的基础SQL猜测了您的CoreData实体/属性名称,但如果我猜错了,请进行调整,例如错误的大写字母。)