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.