I am facing a problem with converting below SQL to NSExpression
SELECT id,trait1,trait2,trait3,sum(trait1+trait2+trait3) as total FROM `bookings` GROUP BY id order by total desc
Below is my code in this code I am only able to add the two key values not three key values.
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)
}
Please find the attached images of actual table values and resulted values for reference.
Thanks!
My Solution:
I am able to solve my problem by doing this
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])
If there is any other way to achieve this, please let me know
Thanks!