title: sql join if value exists in other table then Count it
body: <p>I have following tables.</p>
  
  <p>Table A</p>
  
  <pre> UserID | key<br> 1      | A<br> 2      | B<br> 3      | A<br> 4      | C<br> 5      | <br></pre>
  
  <p>Table B</p>
  
  <pre>UserID | Num<br>1      | 50<br>1      | 300<br>2      |<br>3      | 100<br>4      | 20</pre>
  
  <p>I have query like this</p>
  
  <pre><code>SELECT COUNT(key) AS cnt, key 
  FROM A 
  WHERE key &lt;&gt; '' 
  GROUP BY key 
  ORDER BY cnt DESC
  </code></pre>
  
  <p>The results should be something like this</p>
  
  <pre> key | cnt<br> A   | 2<br> B   | 1<br> C   | 1<br></pre>
  
  <p>What I would like to add is Joining Table B. <br>
  If UserID  has value in Num in Table B, I would like to count UserID with/Num Grouped by key</p>
  
  <p>Here is desired results</p>
  
  <pre> key | cnt | Has Num?<br> A   | 2   | 2<br> B   | 1   | 0<br> C   | 1   | 1<br></pre>
  
  <p>I tried to write subquery but I can't attach it to main query. Subquery is something like this.</p>
  
  <pre><code>SELECT COUNT(DISTINCT UserID) AS num 
  FROM B 
  LEFT OUTER JOIN A ON B.UserID = A.UserID 
  WHERE Num &lt;&gt;'' AND key &lt;&gt; '' 
  GROUP BY key
  </code></pre>