我在将以下 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)
}
请查找实际表值和结果值的附图以供参考。
谢谢!
我的解决方案:
我可以通过这样做来解决我的问题
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])
如果有任何其他方法可以实现这一点,请告诉我
谢谢!