title: Aggregate after join without duplicates
body: <p>Consider this query:</p>
  
  <pre><code>select
     count(p.id),
     count(s.id),
     sum(s.price)
  from 
     (select * from orders where &lt;condition&gt;)   as s,
     (select * from products where &lt;condition&gt;) as p
  where 
     s.id = p.order;
  </code></pre>
  
  <p>There are, for example, 200 records in products and 100 in orders (one order can contain one or more products).</p>
  
  <p>I need to join then and then:</p>
  
  <ol>
  <li>count products (should return 200)  </li>
  <li>count orders (should return 100)  </li>
  <li>sum by one of orders field (should return sum by 100 prices)</li>
  </ol>
  
  <p>The problem is after join <strong>p</strong> and <strong>s</strong> has same length and for <strong>2)</strong> I can write <em>count(distinct s.id)</em>, but for <strong>3)</strong> I'm getting duplicates (for example, if sale has 2 products it sums price twice) so sum works on entire 200 records set, but should query only 100.</p>
  
  <p>Any thoughts how to <em>sum</em> only distinct records from joined table but also not ruin another selects?</p>
  
  <p>Example, joined table has</p>
  
  <pre><code>id sale price
  0  0    4
  0  0    4
  1  1    3
  2  2    4
  2  2    4
  2  2    4
  </code></pre>
  
  <p>So the <strong>sum(s.price)</strong> will return:</p>
  
  <pre><code>4+4+3+4+4+4=23
  </code></pre>
  
  <p>but I need:</p>
  
  <pre><code>4+3+4=11
  </code></pre>