How do I use an SQL GROUP BY and SUM functions in a IOS CORE-DATA request in SWIFT?

前端 未结 1 1757
孤街浪徒
孤街浪徒 2020-12-10 00:29

I have a table (Transactions) which holds records containing the Account_name and an Amount for the transaction. I would like to calculate the total for all transactions per

相关标签:
1条回答
  • 2020-12-10 01:01

    Bear in mind that CoreData is not a relational database, so you should think of entities not "tables", and objects not "records". Note also that by convention, attribute names should not begin with Uppercase letters. That said, it is possible to construct a fetch to achieve what you want. The key steps are:

    1. create a fetch request
    2. specify an NSPredicate to filter according to your chosen criteria
    3. set the resultType to .DictionaryResultType (required for "Group By")
    4. set the properties to be included in the fetch (to get the sum(), this involves creating an NSExpression and associated NSExpressionDescription).
    5. set the properties to group by
    6. Create an NSSortDescriptor to order by name, descending
    7. Execute the fetch

    See the following code:

    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?
    

    The result will be an array of dictionaries, with keys "Account_name" and "sumOfAmount".

    EDIT To extract the value for a particular Account_name, use another predicate:

        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
        }
    

    I've ignored the fact that the previous example filtered Account_name to those beginning "Private", and assumed you will have one (and only one) account with name "toto" (hence filteredResults[0]); your production code should check.

    0 讨论(0)
提交回复
热议问题