私のアプリでは、最も人気のある4つの製品をリストしようとしています。
製品の人気は、注文の合計数量によって決まります。
以下のクエリは、私がやろうとしていることを説明するためのものです。
SELECT TOP 4 SUM(quantity) as sumQuantity, Product
FROM [Order]
GROUP BY Product
ORDER BY 1 DESC
以下のコードは、CoreDataモデルに対するフェッチリクエストで取得するための私のアプローチです。
// 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;
私の問題はsortDescriptorです。これは、Orderの直接プロパティのみを許可しているようです(アプリの例外)。
ソートは、返される4つのレコードを決定するため、非常に重要です。
注:私はMagicalRecordとMogeneratorを使用しています。クラスプレフィックスを削除しました。