2013-02-10 56 views
4

在我的應用程序中,我試圖列出四種最受歡迎​​的產品。
產品受歡迎程度由訂單總量決定。NSFetchRequest總和,分組和排序

下面的查詢是要說明什麼,我試圖做的:

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

下面的代碼是我的方式來得到它在反對我的核心數據模型讀取請求:

// 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,它似乎只允許訂單的直接屬性(應用程序例外)。
這種排序非常重要,因爲它確定將返回哪四條記錄。

注意:我正在使用MagicalRecord和Mogenerator。我已經刪除了類的前綴。

回答

3

不幸的是,NSSortDescriptor想要一個實際的屬性進行排序,而不是動態計算的字段。根據您的情況,您可能希望在模型本身上保存所需的計數器並按其進行排序,或者獲取整個圖形並將其排序在內存中。

+0

在產品中跟蹤計數器對我來說不是一個真正的選擇。我與一臺服務器同步,這樣會很快變得酸滑和不一致。這是一個相當大的限制。儘管感謝您的幫助。 – Zyphrax 2013-02-10 05:05:06