title: Rails/SQL: Group and sum query based on a relational value shared in different table columns
body: <p>I have three tables: <code>Fee</code>, <code>Project</code> and <code>Company</code>:</p>
  
  <pre>
  ------------------   ------------------    ------------------
  |      Fee       |   |     Project    |    |     Company    |
  ------------------   ------------------    ------------------
  | fee:float      |   | id:int         |    | id:int         |  
  | project_id:int |   | currency:string|    | currency:string|
  | ...            |   | company_id:int |    | ...            |
  ------------------   | ...            |    ------------------
                       ------------------
  </pre>
  
  <p>Each <code>Company</code> has many <code>Projects</code> and a <code>Project</code> typically has many <code>Fees</code>. I am trying to group (and sum) <code>Fees</code> by their currency type which, for legacy reasons is now set either on <code>Projects</code> or on <code>Companies</code> (a mess I know, but one I've inherited).</p>
  
  <p>The following <code>ActiveRecord</code> queries nearly do what I require, but not quite:</p>
  
  <pre><code>Fee.all.joins(project: :company)
         .group('projects.currency, companies.currency').sum(:fee)
  ...
  =&gt; {"USD"=&gt;100893.0, "AUD"=&gt;320.0, "GBP"=&gt;10279.99, nil=&gt;4242.42}
  .
  .
  .
  Fee.all.joins(project: :company)
         .group('companies.currency, projects.currency').sum(:fee)
  ...
  =&gt; {nil=&gt;10279.99, "KRW"=&gt;4242.42}
  </code></pre>
  
  <p>I can't figure out how to have both currency columns from (<code>Project</code> and <code>Company</code>) summed correctly in a single query which would return a result like so:</p>
  
  <pre><code> =&gt; {"USD"=&gt;100893.0, "AUD"=&gt;320.0, "GBP"=&gt;10279.99, "KRW"=&gt;4242.42}
  </code></pre>
  
  <p>I could solve this by joining and grouping by one table and column at a time then totalling the results programatically, but that feels clumsy.</p>
  
  <p>EDIT: The full snippet for the first query above (note <code>Fee</code> is implemented as <code>FeeMilestone</code>):</p>
  
  <pre><code>[2] pry(main)&gt; FeeMilestone.joins(project: :company).group('projects.currency, companies.currency').sum(:fee)
  
  (11.0ms)  SELECT SUM("fee_milestones"."fee") AS sum_fee, projects.currency, companies.currency AS projects_currency_companies_currency FROM "fee_milestones" INNER JOIN "projects" ON "projects"."id" = "fee_milestones"."project_id" INNER JOIN "companies" ON "companies"."id" = "projects"."company_id" GROUP BY projects.currency, companies.currency
  
  =&gt; {"USD"=&gt;100893.0, "AUD"=&gt;320.0, "GBP"=&gt;10279.99, nil=&gt;4242.42}
  </code></pre>
  
  <p>I'm hoping to get the <code>Projects.currency</code> to return instead of <code>nil</code> above (it would be <code>"KRW"</code> in my dev environment).</p>