title: T-SQL count distinct and group by distinct IDs
body: <p>I have the following type of table:</p>
  
  <pre><code>BranchName CustID
  ========== ======
  Branch1    1111
  Branch1    1111
  Branch1    2222
  Branch2    2222
  Branch2    4444 
  Branch3    1111
  Branch4    3333
  </code></pre>
  
  <p>What I'm trying to achieve is to count distinct CustID and group them by branches, without repeating any CustID. </p>
  
  <p>Basically I'm trying to get to this:</p>
  
  <pre><code>BranchName DistCountofCust
  ========== ======
  Branch1    2
  Branch2    1
  Branch3    0
  Branch4    1
  </code></pre>
  
  <p>I tried this code:</p>
  
  <pre><code>SELECT X.BranchName, COUNT(DISTINCT X.CustID) as DistCountofCust
  
  FROM
  
  (SELECT T.BranchName, T.CustID
  
  FROM MyTable T) as X
  
  GROUP BY X.BranchName
  </code></pre>
  
  <p>It doesn't give correct result (doesn't count the number of CustID per branch correctly, because CustIDs overlap for certain branches). Is it possible to eliminate distinct CustIDs and group them per given branches? (In the final result I need only unique customers to be listed for branches).</p>