Let's say you want to find the sum of the prices of a bunch of products in your database, and the criteria used for selecting products involve using :include to bring in associated tables. Those LEFT OUTER JOIN statements may result in the base record (Product) being duplicated for every association found. e.g. if product number 1 has three comments associated with it, then Product.sum(:price, :include => :comments, :conditions => ...) will include product number 1 in three rows of the SQL result set. I only want its price added to the sum once, but I can't use the :distinct option because the prices I'm adding up aren't necessarily unique.
This patch adds a :distinct_records option to ActiveRecord::Calculations::ClassMethods#calculate, which replaces the table name in the SQL query with another SQL SELECT query to find a distinct set of records to be summed. I've included a couple tests to illustrate the effect, and I've run this under MySQL. I'm not sure whether all other DBs support this syntax so the patch may need work.