我有一个表(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不是关系数据库,因此您应该考虑的实体不是“表”,而对象不是“记录”。还要注意,按照惯例,属性名称不应以大写字母开头。也就是说,可以构造访存来实现所需的功能。关键步骤是:
NSPredicate
resultType
.DictionaryResultType
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]);您的生产代码应检查。
Account_name
filteredResults[0]