在我的应用程序中,我试图列出四种最受欢迎的产品。
产品的受欢迎程度取决于订单的总数量。
下面的查询是为了说明我想要做的事情:
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。我已经删除了类前缀。
发布于 2013-02-10 04:54:45
不幸的是,NSSortDescriptor希望对实际属性进行排序,而不是动态计算字段。根据您的情况,您可能希望在模型本身上保存所需的计数器并按其排序,或者获取整个图并在内存中对其排序。
https://stackoverflow.com/questions/14794761
复制相似问题