按两个关系分组和总和

时间:2016-05-13 22:50:19

标签: ruby-on-rails activerecord

我有一个ruby on rails应用程序,它有三个模型:transactionevent_sectionaccount。一个事务只属于一个event_section和一个帐户。在transaction的模型中,我有一个方法sum来获取事务的总和,它使用模型的多个字段。 (它添加了amount_coinsamount_billsamount_rolls

我的架构如下所示:

create_table "accounts", force: :cascade do |t|
    t.string   "title",           limit: 255
    t.text     "description",     limit: 65535
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

  create_table "event_sections", force: :cascade do |t|
    t.string   "title",       limit: 255
    t.text     "description", limit: 65535
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "transactions", force: :cascade do |t|
    t.datetime "created_at",          null: false
    t.datetime "updated_at",          null: false
    t.integer  "account_id",          limit: 4
    t.integer  "amount_bills",        limit: 4
    t.decimal  "amount_coins",        precision: 64, scale: 2
    t.integer  "amount_rolls",        limit: 4
    t.integer  "event_section_id",    limit: 4
  end

  add_index "transactions", ["account_id"], name: "fk_rails_01f020e267", using: :btree
  add_index "transactions", ["event_section_id"], name: "fk_rails_b5ed204601", using: :btree

现在我想有效地生成一个表accountsevent_sections作为行和列,这些单元格应该是具有相应的所有事务的sum函数的总和event_sectionaccount

       |  ES1    | ES2       |
|------|---------|-----------|
| Acc1 | 845.00  |  1'285.00 |
| Acc2 | 1080.00 |    345.00 |

要获取此表,以下示例数据将位于数据库中:

Account.create(title: "Acc1") -> id = 1
Account.create(title: "Acc2") -> id = 2

EventSection.create(title: "ES1") -> id = 1
EventSection.create(title: "ES2") -> id = 2

Transaction.create(amount_coins: 10, amount_bills: 500, amount_rolls: 15, account_id: 1, event_section_id: 1)
Transaction.create(amount_coins: 10, amount_bills: 300, amount_rolls: 10, account_id: 1, event_section_id: 1)
Transaction.create(amount_coins: 30, amount_bills: 700, amount_rolls: 30, account_id: 2, event_section_id: 1)
Transaction.create(amount_coins: 10, amount_bills: 300, amount_rolls: 10, account_id: 2, event_section_id: 1)

Transaction.create(amount_coins: 10, amount_bills: 300, amount_rolls: 35, account_id: 1, event_section_id: 2)
Transaction.create(amount_coins: 30, amount_bills: 900, amount_rolls: 10, account_id: 1, event_section_id: 2)
Transaction.create(amount_coins: 25, amount_bills: 300, amount_rolls: 20, account_id: 2, event_section_id: 2)

(当然我可以写一个double for循环,但我知道这样做效率不高。我也可以编写简单的SQL,但是如果可以的话,每个人都说你应该使用rails魔法。)

感谢您的帮助!

0 个答案:

没有答案