Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's very probably that I am totally wrong. I feel you simplify your problem too much in order to let others understand it. Since I can't give this well-formatted code in a comment, I input the answer here.</p> <pre><code>SELECT users.*, users.computed_metric, users.age_in_seconds, ( users.computed_metric / age_in_seconds) as compound_computed_metric from ( select users.*, (users.id *2 ) as computed_metric, (extract(epoch from now()) - extract(epoch from users.created_at) ) as age_in_seconds from users ) as users </code></pre> <p>Below SQL is equivalent to your above SQL. That's why I say the sub-query is not necessary.</p> <pre><code>select users.*, (users.id *2 ) as computed_metric, (extract(epoch from now()) - extract(epoch from users.created_at) ) as age_in_seconds, computed_metric/age_in_seconds as compound_computed_metric from users </code></pre> <p>If that's right, then the compound_computed_metric can be calculated in below way. No custom query is needed.</p> <pre><code>class User &lt; ActiveRecord::Base def compound_computed_metric computed_metric/age_in_seconds end def computed_metric self.id * 2 end def age_in_seconds Time.now - self.created_at end end 1.9.3p327 :001 &gt; u = User.first User Load (0.1ms) SELECT "users".* FROM "users" LIMIT 1 =&gt; #&lt;User id: 1, name: "spider", created_at: "2013-08-10 04:29:35", updated_at: "2013-08-10 04:29:35"&gt; 1.9.3p327 :002 &gt; u.compound_computed_metric =&gt; 1.5815278998954843e-05 1.9.3p327 :003 &gt; u.age_in_seconds =&gt; 126471.981447 1.9.3p327 :004 &gt; u.computed_metric =&gt; 2 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload