Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #6552 (closed enhancement: duplicate)

Opened 4 years ago

Last modified 3 years ago

[PATCH] Calculations supports multiple aggregate operations

Reported by: BobSilva Assigned to: David
Priority: normal Milestone: 1.2.5
Component: ActiveRecord Version: edge
Severity: normal Keywords: calculations
Cc:

Description

This patch modifies the Calculations module to support multiple aggregate operations in one query. It also adds support for specifiying the column alias. This allows you to specify the column alias in the method call for use in an order by for example, without looking at the source to see how it generates the column alias.

min, max = Person.calculate(:min, :age, :max, :age)
opened, closed = Tickets.sum(:opened, :closed)

ordered_posts = Post.sum({:replies => 'post_replies'}, :order => 'post_replies') 

This patch also adds ArgumentErrors for using :distinct on groups when using an adapter which doesn't support count(distinct). Before it would just error out silently.

Once (if) this patch is applied, I will work on adding multiple grouping column facilities in accordance with the SQL standard.

A full test suite is provided.

Attachments

multiple_calculations.5434.diff (31.0 kB) - added by BobSilva on 11/05/06 20:38:06.
Tested in mysql and sqlite 2 and 3

Change History

11/05/06 20:38:06 changed by BobSilva

  • attachment multiple_calculations.5434.diff added.

Tested in mysql and sqlite 2 and 3

11/05/06 21:24:10 changed by BobSilva

One thing to point out that caught bitsweats eye, using the :op, :column, ... style is a technical limitation of the current implementation. Since the current calculations return only the value and not the column name, this makes the ordering of the columns relevant which is lost if you use a hash. The possible alternative to this is to return multiple calculations using a hash instead of an array of values.

Currently:

Model.sum(:column1) => 50
Model.sum(:column1, :column2) => [50, 60]
Model.calculate(:sum, :column1, :sum, {:column2 => 'sum_for_column2'}) 
 => [50, 60]

Alternatively, it could use hashed results for multiple calculations which in turn allows specifying the arguments as a hash:

Model.sum(:column1) => 50
Model.sum(:column1, :column2) => {:sum_column1 => 50, :sum_column2 => 60}
Model.calculate(:sum => :column1, :sum => {:column2 => 'sum_for_column2'} )
 => {:sum_column1 => 50, :sum_for_column2 => 60}

10/08/07 06:49:59 changed by tarmo

  • status changed from new to closed.
  • resolution set to duplicate.

Closing this in favor of #9487