title: SQL - Use results of a query as basis for two other queries in one statement
body: <p>I'm doing a probability calculation. I have a query to calculate the total number of times an event occurs. From these events, I want to get the number of times a sub-event occurs. The query to get the total events is 25 lines long and I don't want to just copy + paste it twice. </p>
  
  <p>I want to do two things to this query: calculate the number of rows in it, and calculate the number of rows in the result of a query on this query. Right now, the only way I can think of doing that is this (replace @total@ with the complicated query to get all rows, and @conditions@ with the less-complicated conditions that rows, from @total@, must have to match the sub-event): </p>
  
  <pre><code>SELECT (SELECT COUNT(*) FROM (@total@) AS t1 WHERE @conditions@) AS suboccurs, 
         COUNT(*) AS totaloccurs FROM (@total@) as t2
  </code></pre>
  
  <p>As you notice, @total@ is repeated twice. Is there any way around this? Is there a better way to do what I'm trying to do?</p>
  
  <p>To re-emphasize: @conditions@ does depend on what @total@ returns (it does stuff like <code>t1.foo = bar</code>).</p>
  
  <p>Some final notes: @total@ by itself takes ~250ms. This more complicated query takes ~300ms, so postgres is likely doing some optimization, itself. Still, the query looks terribly ugly with @total@ literally pasted in twice.</p>