2016-12-22 38 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