title: Calculate COUNT in GROUP BY SQL query
body: <p>I have query to calculate total amount by one product item below:</p>
  
  <pre><code>SELECT p.[Id], COUNT(o.[Id]), SUM(o.[Amount])
  FROM [dbo].[Order] o
      INNER JOIN [dbo].[Product] p ON p.[Id] = o.[ProductId]
  GROUP BY p.[Id]
  </code></pre>
  
  <p>In this case, COUNT(o.[Id]) is number of unique orders by one product item.</p>
  
  <p>But instead of COUNT(o.[Id]) I would like to calculate number of orders using next formula:</p>
  
  <pre><code>COUNT(o.[OwnerId]) -- where o.[OwnerId] IS NOT NULL
  +
  COUNT(o.[Id]) -- where o.[OwnerId] IS NULL
  </code></pre>
  
  <p>Could I implement it in one query? What solution will be better for performance?</p>
  
  <p>UPDATE:</p>
  
  <p>I am so sorry for my fast finish. Mahmoud Gamal provides nice example, but it calculates a bit else.</p>
  
  <pre><code>SELECT
      p.[Id],
      COUNT(DISTINCT CASE WHEN o.[OwnerId] IS NOT NULL THEN o.[OwnerId] ELSE NULL END) AS [NumberOfOrderOwners],
      SUM(CASE WHEN o.[OwnerId] IS NULL THEN 1 ELSE 0 END) AS [NumberOfAnonimousOwners],
      SUM(o.[Amount])
  FROM [dbo].[Order] o
      INNER JOIN [dbo].[Product] p ON p.[Id] = o.[ProductId]
  GROUP BY p.[Id]
  </code></pre>
  
  <p>Query above calculates as I need, but estimated cost is increased in twice because I use DISTINCT inside of COUNT.</p>
  
  <p>Could anybody help me to improve my query?</p>