以下の SQL を NSExpression に変換する際に問題に直面しています
SELECT id,trait1,trait2,trait3,sum(trait1+trait2+trait3) as total FROM `bookings` GROUP BY id order by total desc
以下は、このコードの私のコードで、3 つのキー値ではなく 2 つのキー値しか追加できません。
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])
これを達成する他の方法がある場合は、私に知らせてください
ありがとう!