5

私のアプリでは、最も人気のある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を使用しています。クラスプレフィックスを削除しました。

4

1 に答える 1

3

残念ながら、NSSortDescriptor動的に計算されたフィールドではなく、実際のプロパティを並べ替える必要があります。状況に応じて、必要なカウンターをモデル自体に保存して並べ替えるか、グラフ全体をフェッチしてメモリに並べ替えます。

于 2013-02-10T04:54:45.267 に答える