将SQL语句转换为谓词或NSExpression

时间:2016-09-21 12:03:42

标签: xcode sqlite core-data nspredicate nsexpression

我遇到了将SQL转换为NSExpression

的问题
SELECT id,trait1,trait2,trait3,sum(trait1+trait2+trait3) as total FROM `bookings` GROUP BY id order by total desc

下面是我在此代码中的代码我只能添加两个键值而不是三个键值。

func aggregateProductsInContext(context:NSManagedObjectContext) {

    var expressionDescriptions = [AnyObject]()
    expressionDescriptions.append("name")

    let expressionDescription = NSExpressionDescription()
    expressionDescription.name = "Sold"

    let exp1 = NSExpression(forKeyPath: "trait1")
    let exp3 = NSExpression(forKeyPath: "trait2")
    let exp3 = NSExpression(forKeyPath: "trait3")

    let stas = NSExpression(forFunction:"add:to:", arguments:[exp1,exp3])

    expressionDescription.expression = stas
    expressionDescription.expressionResultType = .Integer64AttributeType
    expressionDescriptions.append(expressionDescription)
    let request = NSFetchRequest(entityName: "booking")
    request.propertiesToGroupBy = ["name"]
    request.resultType = .DictionaryResultType
    request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
    request.propertiesToFetch = expressionDescriptions



    var results:[[String:AnyObject]]?

    do {
        results = try context.executeFetchRequest(request) as? [[String:AnyObject]]
    } catch _ {
        results = nil
    }



print(results)

}

请查看实际表格值和结果值的附图,以供参考。

ActualData image

Result Data after run the Sql query

谢谢!

我的解决方案:

我能够通过这样做来解决我的问题

let ec = NSExpression(forFunction:"add:to:", arguments:[exp1,exp2])
let ec1 = NSExpression(forFunction:"add:to:", arguments:[ec,exp3])
let ec2 = NSExpression(forFunction:"add:to:", arguments:[ec1,exp4])
let ec3 = NSExpression(forFunction:"add:to:", arguments:[ec2,exp5])

如果还有其他方法可以实现此目的,请告诉我

谢谢!

1 个答案:

答案 0 :(得分:0)

这是我实施的解决方案,它的工作正常。

let ec = NSExpression(forFunction:"add:to:", arguments:[exp1,exp2])
let ec1 = NSExpression(forFunction:"add:to:", arguments:[ec,exp3])
let ec2 = NSExpression(forFunction:"add:to:", arguments:[ec1,exp4])
let ec3 = NSExpression(forFunction:"add:to:", arguments:[ec2,exp5])

但我相信必须有其他一些好的方法来做到这一点。如果有人有任何其他解决方案。请告诉我。

谢谢!