简体   繁体   中英

coredata - fetch distinct rows having maximum value

I'm trying to setup my NSFetchRequest to core data to retrieve the rows "unique name which have greater rate"

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"rate = max(rate)"];
[request setPropertiesToFetch:@[@"name"]];
request.predicate = predicate;
[request setReturnsDistinctResults:YES];

But the above return only one row which have maximum rate.

required sample

  name | rate | factor |
_______|______|________|
John   |  3.2 |    7   |
Betty  |  5.5 |    7   |
Betty  |  7.1 |    2   |
Betty  |  3.1 |    2   |
Edward |  5.5 |    1   |
Edward |  4.5 |    2   |
John   |  4.3 |    4   |

How would i set up the request to return an array like

John,  4.3, 4
Betty, 7.1, 2
Edward,5.5, 1

And can we sort it (sort by rate desc) with the fetch query itself ? So the result array will be

Betty, 7.1, 2
Edward,5.5, 1
John,  4.3, 4

Set the propertiesToGroupBy property of your NSFetchRequest to include "name".

Note: you may have to aggregate the factor column in some way as well, for the group by to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM