0

以下の 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)

}

実際のテーブル値と結果値の添付画像を参考にしてください。

実際のデータ画像

Sql クエリを実行した後の結果データ

ありがとう!

私の解決策:

これを行うことで問題を解決できます

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])

これを達成する他の方法がある場合は、私に知らせてください

ありがとう!

4

1 に答える 1

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])

しかし、それを行うための他の良い方法があるに違いないと確信しています。誰かが他の解決策を持っている場合。私にお知らせください。

ありがとう!

于 2016-09-22T04:54:24.830 に答える