5

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.

Yvo
  • 18,681
  • 11
  • 71
  • 90

1 Answers1

3

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.

Dmitry Shevchenko
  • 31,814
  • 10
  • 56
  • 62
  • Keeping track with a counter in Product isn't really an option for me. I sync with a server so that would go sour and inconsistent pretty quickly. This is quite a huge limitation. Thanks for your help though. – Yvo Feb 10 '13 at 05:05