【问题标题】:strftime SQL function in Core data核心数据中的 strftime SQL 函数
【发布时间】:2016-01-22 22:46:04
【问题描述】:

我正在尝试在 Core Data 中进行提取,并按我的财产日期的月份分组。

在 SQL 中

SELECT      SUM(total) as value,
            date as date,
            strftime('%m-%Y', date) as convertDate  
FROM        table
GROUP BY    convertDate 

我没有看到任何可以使用strftime 的功能。 有没有办法用NSFetchRequest 而不是NSFetchedResultController 来做到这一点?

【问题讨论】:

  • 不,CoreData 没有 strftime 或 DATEPART 等效项。它的 groupby 仅适用于持久属性,而不适用于计算表达式。如果您想通过 fetchRequest 实现此目的,则必须为计算的月/年添加一个持久属性,并确保它与日期保持同步。
  • 这就是我所担心的。我知道 Core Data 不是 ORM,但我有点失望。谢谢

标签: ios objective-c core-data nsfetchedresultscontroller nsfetchrequest


【解决方案1】:

你可以使用NSExpressionDescription来做到这一点

对于按 NSFetchRequest 分组,您可以看到 this tutorial 或此 stackOverFlow question

这里的总和 NSExpressionDescription 添加到您的 NSFetchRequest

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
expressionDescription.name = @"sumOfAmounts";
expressionDescription.expression = [NSExpression expressionForKeyPath:@"@sum.total"];
expressionDescription.expressionResultType = NSDecimalAttributeType;

对于日期,我认为您可以在获取获取记录时使用NSDateFormatter 对其进行格式化。

如果这有帮助,请告诉我:)

更新

[fetch setPropertiesToFetch:[NSArray arrayWithObjects:statusDesc, expressionDescription, nil]];
[fetch setPropertiesToGroupBy:[NSArray arrayWithObject:statusDesc]];
[fetch setResultType:NSDictionaryResultType];
NSError* error = nil;
NSArray *results = [myManagedObjectContext executeFetchRequest:fetch
                                                         error:&error];

【讨论】:

  • 感谢您的回答。我唯一的问题是在 nsfetchrequest 中按月分组。我不想在请求后分组
  • 我认为在教程中是这样的。查看我的更新
  • 获取的是 NSFetchRequest
  • 我知道我需要创建一个 nsexpression 但我怎样才能得到日期中的月份。 nsrequest 中没有获取它的函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
  • 1970-01-01
  • 2011-01-11
  • 2011-10-16
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多