【问题标题】:Efficient sum / group by query in Rails using SQLite使用 SQLite 在 Rails 中高效求和/分组查询
【发布时间】:2012-02-19 16:24:29
【问题描述】:

我正在使用 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"

我的目标是查询凭证日期

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

我想我需要两个查询(一个用于借方的总和,一个用于贷方的总和),但我认为它比使用 rails-functions 更有效。谁能帮我这样的查询应该是什么样子? 非常感谢!

【问题讨论】:

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


    【解决方案1】:

    以下是获取每个帐户每月贷方和借方总和的 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​​ 代码交叉表或将数据转换为您需要的格式。如果您在这方面需要帮助,请随时发布新问题。

    【讨论】:

      猜你喜欢
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多