2012-02-19 3 views
0

私はSQLite3を使用しており、数字フィールドの合計を月単位で取得したいと考えています。モデルは次のようになります。SQLiteを使用したRailsのクエリによる効率的な合計/グループ

# 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" 

私の目標は、すなわち

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

私が思うに、voucherdateは< 12月転記を照会し、各口座番号のdebitentries/creditentriesの合計euroamount和を得ることです2つのクエリが必要になります(デビットエントリーとクレデンシャルのためのもの)が必要ですが、rails-functionsを使うよりはるかに効率的です。どのようにそのようなクエリがどのように表示される必要があります誰も助けることができますか? 事前に感謝します!ここで

答えて

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) 

結果は次のようになります。レールに任意のSQLを実行するため

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 

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

ここから、旧式のルビーコードを使用して必要な形式にデータをクロスタブまたはピボットする必要があります。あなたがそれについての助けを必要とするならば、新しい質問を投稿してください。

関連する問題