title: Interview Question about SQL group by and having
body: <p>This problem is from the following</p>
  
  <p><a href="https://www.programmerinterview.com/index.php/database-sql/advanced-sql-interview-questions-and-answers/" rel="nofollow noreferrer">https://www.programmerinterview.com/index.php/database-sql/advanced-sql-interview-questions-and-answers/</a></p>
  
  <p>Assume we have two tables: </p>
  
  <pre><code>Salesperson 
  ID  Name    Age Salary
  
  
  Orders
  Number  order_date  cust_id salesperson_id  Amount
  </code></pre>
  
  <p>The question is following: </p>
  
  <p>We want to retrieve the names of all salespeople that have more than 1 order from the tables above. You can assume that each salesperson only has one ID. I would probably also assume that names are all distinct.</p>
  
  <p>My answer was this. </p>
  
  <pre><code>select Name from 
  salesperson S inner join Orders O 
  on S.ID=O.salesperson_id 
  group by Name 
  having count(number) &gt;=2
  </code></pre>
  
  <p>However, the given answer is following:</p>
  
  <pre><code>SELECT Name
  FROM Orders inner join Salesperson
  On Orders.salesperson_id = Salesperson.ID
  GROUP BY salesperson_id, NAME
  Having count(salesperson_id) &gt; 1
  </code></pre>
  
  <p>If name and salesperson_id is one to one, is there any reason we have to add salesperson_id into the group by statement here? Also, if name and salesperson_id relationship is just one to one, wouldn't count(salesperson_id) be always 1 if we group by salesperson_id, name?</p>
  
  <p>I was a bit confused about this, and I was wondering if anybody encountered this problem before and found this weird as well. </p>