使用SQLite在Rails中进行查询的高效求和/分组

时间:2012-02-19 16:24:29

标签: sql ruby-on-rails ruby-on-rails-3 sqlite

我正在使用SQLite3,并希望按月获得数字字段的总计。模型看起来像:

    # Table name: accounts
    #  id               :integer         not null, primary key
    #  created_at       :datetime
    #  updated_at       :datetime

    class Account < ActiveRecord::Base
    has_many :debitentries, :class_name => "Posting", :foreign_key => "debitaccount_id"
    has_many :creditentries, :class_name => "Posting", :foreign_key => "creditaccount_id"


    # Table name: postings
    #  id               :integer         not null, primary key
    #  voucherdate      :date
    #  debitaccount_id  :integer
    #  creditaccount_id :integer
    #  euroamount       :decimal(, )

    Class Postings  < ActiveRecord::Base
    belongs_to :debitaccount, :class_name => "Account", :foreign_key => "debitaccount_id"
    belongs_to :creditaccount, :class_name => "Account", :foreign_key => "creditaccount_id"

我的目标是查询voucherdate&lt; 12个月并获得每个帐号的借方或贷方的总欧元金额,即

    Account.id| Feb 2012 | Jan 2012 | Dec 2011 | ... | Mar 2011
    ------------------------------------------------------------
       1      |   233.87 | 123.72   | ...      |     | sum(euroamount)
       2      |    ...   |          |          |     |

我想我需要两个查询(一个用于借记条件,一个用于信用条件),但我认为它比使用rails-functions更有效。任何人都可以帮助我这样的查询将如何看起来像? 非常感谢提前!

1 个答案:

答案 0 :(得分:0)

这是每个帐户按月获得信用卡和借记卡的SQL:

Select accounts.id, 
strftime('%B %Y', voucherdate) month,
sum(credits.euroamount) total_credits,
sum(debits.euroamount) total_debits
from accounts
join postings as credits
  on accounts.id = creditaccount_id
join postings as debits
  on accounts.id = debitaccount_id
group by accounts.id, strftime('%B %Y', voucherdate)

结果如下:

id     | month          | total_credits | total_debits
-------------------------------------------------------
1      | January 2011   | 243.12        | 123.12
1      | February 2011  | 140.29        | 742.22
1      | March 2011     | 673.19        | 238.11
2      | January 2011   | 472.23        | 132.14
2      | February 2011  | 365.34        | 439.99

在rails中执行任意sql:

account_id_hash = ActiveRecord::Base.connection.select_all("Select accounts.id from accounts")

从这里开始,您需要使用老式的ruby代码将数据交叉制表或转换为您需要的格式。如果您需要帮助,请随时发布新问题。