Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFetchRequest sum, group by and sorting

In my app I'm trying to list the four most popular products.
The product popularity is determined by the total quantity in orders.

The query below is to illustrate what I'm trying to do:

SELECT     TOP 4  SUM(quantity) as sumQuantity, Product
FROM       [Order]
GROUP BY   Product
ORDER BY   1 DESC

The code below is my approach to getting it in a fetch request against my Core Data model:

// Create an expression to sum the order quantity
NSExpressionDescription *sumExpression = [[NSExpressionDescription alloc] init];
sumExpression.name = @"sumQuantity";
sumExpression.expression = [NSExpression expressionWithFormat:@"@sum.%K", OrderAttributes.quantity];
sumExpression.expressionResultType = NSInteger32AttributeType;

// Create the fetch request
NSFetchRequest *request = [Order createFetchRequest];
request.resultType = NSDictionaryResultType;
request.propertiesToFetch = @[OrderRelationships.product, sumExpression];
request.propertiesToGroupBy = @[OrderRelationships.product];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:sumExpression.name ascending:NO]];
request.fetchLimit = 4;

My problem is the sortDescriptor, it only seems to allow direct properties of Order (app exception).
The sort is extremely important, because it determines which four records will be returned.

Note: I'm using MagicalRecord and Mogenerator. I've removed the class prefixes.

like image 351
Zyphrax Avatar asked Oct 21 '22 17:10

Zyphrax


1 Answers

Unfortunately, NSSortDescriptor wants an actual property to sort on, not dynamically calculated field. Depending on your situation, you would want to either save required counter on a model itself and sort by it, or fetch the whole graph and sort it in memory.

like image 106
Dmitry Shevchenko Avatar answered Oct 24 '22 18:10

Dmitry Shevchenko