我有一个表(Transactions),其中包含包含Account_name和交易金额的记录.我想计算每个帐户的所有交易的总额,以“私人”开头,交易金额为> 1000.我想按名称按降序排列帐户.
所以sql请求会是这样的:
SELECT Account_name,SUM(Amount) FROM Transactions WHERE Account_name like 'Private%' and Amount > 1000 GROUP BY Account_name ORDER BY Account_name DESC
我如何在Swift中使用Core-DATA来做到这一点.
谢谢
请记住,CoreData不是关系数据库,因此您应该认为实体不是“表”,对象不是“记录”.另请注意,按照惯例,属性名称不应以大写字母开头.也就是说,可以构造一个fetch来实现你想要的.关键步骤是:
原文链接:https://www.f2er.com/swift/319985.html>创建一个获取请求
>根据您选择的标准指定NSPredicate进行过滤
>将resultType设置为.DictionaryResultType(“分组依据”必需)
>设置要包含在fetch中的属性(获取sum(),这涉及创建NSExpression和关联的NSExpressionDescription).
>将属性设置为分组依据
>创建一个NSSortDescriptor按名称降序排序
>执行提取
请参阅以下代码:
let fetch = NSFetchRequest(entityName: "Transaction") let predicate = NSPredicate(format: "Account_name like %@ AND Amount > %@","Private*",NSNumber(double: 1000.0)) fetch.predicate = predicate fetch.resultType = .DictionaryResultType let sumExpression = NSExpression(format: "sum:(Amount)") let sumED = NSExpressionDescription() sumED.expression = sumExpression sumED.name = "sumOfAmount" sumED.expressionResultType = .DoubleAttributeType fetch.propertiesToFetch = ["Account_name",sumED] fetch.propertiesToGroupBy = ["Account_name"] let sort = NSSortDescriptor(key: "Account_name",ascending: false) fetch.sortDescriptors = [sort] let results = managedObjectContext?.executeFetchRequest(fetch,error: nil) as NSArray?
结果将是一个字典数组,其键为“Account_name”和“sumOfAmount”.
编辑
要提取特定Account_name的值,请使用另一个谓词:
let newPredicate = NSPredicate(format: "Account_name like %@","toto")! if let resultsArray = results { // to unwrap the optional let filteredResults = resultsArray.filteredArrayUsingPredicate(newPredicate) let sumOfAmount = (filteredResults[0] as NSDictionary)["sumOfAmount"] as Double }
我忽略了前一个示例将Account_name过滤为以“Private”开头的事实,并假设您将拥有一个(且只有一个)名称为“toto”的帐户(因此filteredResults [0]);你的生产代码应该检查.