I want to get the sums for a dozen columns in a table.
# result will be {:a => 340.5, :b => 21.8, ... }
# where :a has the sum of the :a column values
# entries is an ActiveRecord model, e.g. ScoreCard.where(:user => user)
def self.totals(entries)
[:a, :b, :c, :d, :e, :f, :g, :h, :i, :j, :k, :m].inject({}) do |tv, col|
tv[col] = entries.sum(col)
tv
end
end
Is there a way to do this in one query? The above generates a dozen queries.
You could do something with manually overriding the
selectvalues like this, which would run a single query returning all of your sums as fields: