2016-09-21 45 views
0

我現在面臨一個問題,下面SQL轉換爲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]) 

如果有任何其他的方式來實現這一點,請讓我知道

謝謝!

+0

看到這個解決方案http://stackoverflow.com/a/22398620/2031707 – Punita

+0

你有沒有考慮過使用'sum:'函數'NSExpression'? –

+0

@TomHarrington是的,它只適用於一列。 –

回答

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

但我相信肯定還有其他一些好方法可以做到這一點。如果任何人有其他解決方案。請告訴我。

謝謝!