2016-12-22 40 views
0

我有這種形式的SQL結果:分配多個SQL結果值相同的密鑰

Id Amount1 Amount2 Amount3 
1 10  10  12 
2 20  13  14 
3 30  15  15 

我想的Id的項和所有其他值存儲在值

這樣的事情:

{1=>{:Amount1=>"10", :Amount2=>"10", :Amount3=>"12"}, 2=>{:Amount1=>"20", :Amount2=>"13", :Amount3=>"14"}} 

這是我目前有至今:

hashn = Hash.new 

    sqlresult.each { |x| 
    hashn[x['PPS_Id']] = x['Gift_Card_Amount1'] 
    hashn[x['PPS_Id']] = x['Gift_Card_Amount2'] 
    hashn[x['PPS_Id']] = x['Gift_Card_Amount3'] 
} 

我相信這覆蓋了以前的價值,請你幫忙。

回答

1

您可以分配一個數組的哈希鍵以及

喜歡的東西folllowing

hashn= {} 

    sqlresult.each { |x| 
    hashn[x['PPS_Id']] = [] unless hashn[x['PPS_Id']] 
    hashn[x['PPS_Id']] << x['Gift_Card_Amount1'] 
    hashn[x['PPS_Id']] << x['Gift_Card_Amount2'] 
    hashn[x['PPS_Id']] << x['Gift_Card_Amount3'] 
    } 
0

假設你的SQL結果是積極的記錄集,這應該工作:

required_hash = {} 
sqlresult.each do |obj| 
    required_hash[obj.id] = 
    { amount1: obj.amount1, amount2: obj.amount2, amount3: obj.amount3 } 
end 
required_hash