title: Limit number of rows per group from join (NOT to 1 row)
body: <p>Given these tables:</p>
  
  <pre><code>TABLE Stores (
   store_id INT,
   store_name VARCHAR,
   etc
  );
  
  TABLE Employees (
   employee_id INT,
   store_id INT,
   employee_name VARCHAR,
   currently_employed BOOLEAN,
   etc
  );
  </code></pre>
  
  <p>I want to list the 15 longest-employed employees for each store (let's say the 15 with lowest <code>employee_id</code>), or ALL employees for a store if there are 15 who are <code>currently_employed='t'</code>. I want to do it with a join clause.</p>
  
  <p>I've found a lot of examples of people doing this <strong>only</strong> for 1 row, usually a min or max (single longest-employed employee), but I want to basically do combine an <code>ORDER BY</code> and a <code>LIMIT</code> inside of the join. Some of those examples can be found here:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/2978726/limit-results-from-joined-table-to-one-row">Limit results from joined table to one row</a></li>
  <li><a href="https://stackoverflow.com/questions/20353403/mysql-returning-1-image-for-each-product?lq=1">MySQL returning 1 image for each product</a></li>
  </ul>
  
  <p>I've also found decent examples for doing this store-by-store (I don't, I have about 5000 stores):</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/12113699/get-top-n-records-for-each-group-of-grouped-results">Get top n records for each group of grouped results</a></li>
  </ul>
  
  <p>I've also seen that you can use <code>TOP</code> instead of <code>ORDER BY</code> and <code>LIMIT</code>, but not for PostgreSQL.</p>
  
  <p>I reckon that a join clause between the two tables isn't the only (or even necessarily best way) to do this, if it's possible to just work by distinct <code>store_id</code> inside of the employees table, so I'd be open to other approaches. Can always join afterwards.</p>
  
  <p>As I'm very new to SQL, I'd like any theory background or additional explanation that can help me understand the principles at work.</p>