ios - Needed help for complex core data query -
i have table called userprofile mention below
i need distinct location, count distinct location , count status value 0 @ distinct location user = user1. status value can between 0 t0 5(number)
so output be
abc 3 2 abd 1 1
where abc unique location, 3 total count abc in table , 2 total count status =0 @ location abc
i can give inspiration, due assume, 'status' can 0 or 1. if that's not true, - think - have execute 2 separated fetch different predicated (one fetch count of location referring user1 , other count of status user = user1 , status = 1).
nsfetchrequest *fetchrequest = [[nsfetchrequest alloc] init]; //create entity nsentitydescription *entity = [nsentitydescription entityforname:@"userprofile" inmanagedobjectcontext:self.managedobjectcontext]; [fetchrequest setentity:entity]; //filter user = user1 nspredicate *predicate = [nspredicate predicatewithformat:@"user == %@",user1]; [fetchrequest setpredicate:predicate]; //count of 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 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 0 status !!!important, working if 'status' can 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);
Comments
Post a Comment