Re: [問題] RoR 關於 資料庫 query 的問題

看板Ruby作者 (godfat 真常)時間16年前 (2008/10/05 01:42), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/4 (看更多)
※ 引述《WuHome (Wu)》之銘言: : 原始資料庫內容 : 唱片名稱 購買地點 類別 價錢 購買日期 : AAA 台北 DVD 20 20081001 : BBB 台中 DVD 25 20081001 : CCC 台中 CD 10 20081002 : DDD 台北 DVD 30 20081002 : EEE 台中 DVD 20 20081002 : FFF 台北 CD 10 20081003 : GGG 台北 DVD 20 20081003 : 我希望能列出 我指定的日期 (比如1001 ~ 1002) : 1001 台北 1 總價:20 : 台中 1 總價:25 : DVD 2 總價:45 : CD 0 總價:0 : 1001 台北 1 總價:30 ^^^^ 打錯?是不是 1002 ? : 台中 2 總價:30 : DVD 2 總價:50 : CD 1 總價:10 : 不知道這樣有沒有比較清楚? 如果我猜的沒錯的話,你要的結果還滿複雜的, 我會建議用 ruby 算,或是在 database 存 cache 直接撈出來 用 ruby 很容易,用 group_by 和 inject 即可,例如... (以下 code 完全憑我的想像,沒測試過,可能需要調整) Order.between(start, end).group_by{ |order| order.datadate }.map{ |date_orders| {:date => date_orders.first, :items => date_orders.last.inject({}){ |result, order| result[order.location] ||= { :quantity => 0, :price_total => 0 } result[order.location][:quantity] += 1 result[order.location][:price_total] += order.price result }.merge(date_orders.last.inject({}){ |result, order| result[order.kind] ||= { :quantity => 0, :price_total => 0 } result[order.kind][:quantity] += 1 result[order.kind][:price_total] += order.price result }) } } 上面有重複的部份,可以再提出來寫成: Order.between(start, end).group_by{ |order| order.datadate }.map{ |date_orders| {:date => date_orders.first, :items => [:location, :kind].inject({}){ |items, msg| items.merge( date_orders.last.inject({}){ |result, order| result[order.send(msg)] ||= { :quantity => 0, :price_total => 0 } result[order.send(msg)][:quantity] += 1 result[order.send(msg)][:price_total] += order.price }) } } } 這樣的結果就是: [{:date => '1001', :items => {'台北' => {:quantity => 1, :price_total => 20}, '台中' => {:quantity => 1, :price_total => 25}, 'CD' => {:quantity => 0, :price_total => 0}, 'DVD' => {:quantity => 2, :price_total => 45}}}, {:date => '1002', :items => '略'}] 印出來就... <%= result.map{ |row| row[:date].to_s + row[:items].inject([]){ |result, info| " #{info.first} #{info.last[:quantity]} 總價:#{info.last[:price_total]}" }.join("<br/>#{'&nbsp;'*row[:date].to_s.size}") }.join('<br/>') %> 我可能寫得複雜些了,你可以拆成好幾部份處理 -- In Lisp, you don't just write your program down toward the language, you also build the language up toward your program. 《Programming Bottom-Up》- Paul Graham 1993 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.135.28.18

10/05 01:57, , 1F
先推再試
10/05 01:57, 1F
文章代碼(AID): #18vwiNmN (Ruby)
文章代碼(AID): #18vwiNmN (Ruby)