【问题标题】:NSFetchRequest sum, group by and sortingNSFetchRequest求和、分组和排序
【发布时间】:2013-02-10 04:35:59
【问题描述】:

在我的应用中,我试图列出四种最受欢迎​​的产品。
产品受欢迎程度由订单总量决定。

下面的查询是为了说明我正在尝试做的事情:

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,它似乎只允许 Order 的直接属性(应用程序例外)。
排序非常重要,因为它决定了返回哪四条记录。

注意:我正在使用 MagicalRecord 和 Mogenerator。我已经删除了类前缀。

【问题讨论】:

    标签: objective-c sorting core-data group-by nsfetchrequest


    【解决方案1】:

    不幸的是,NSSortDescriptor 想要一个实际的属性来排序,而不是动态计算的字段。根据您的情况,您可能希望在模型本身上保存所需的计数器并按其排序,或者获取整个图形并在内存中对其进行排序。

    【讨论】:

    • 跟踪产品中的计数器对我来说并不是一个真正的选择。我与服务器同步,这样很快就会变酸和不一致。这是一个相当大的限制。不过感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2016-07-20
    • 2021-04-18
    相关资源
    最近更新 更多