title: How can I query T-SQL to get "Top 10 'x' for each of 'y'
body: <p>OK, I've found some close references to what I'm trying to do, but the examples given and the answers were either too simple for me to extrapolate from, or too complex for me to grasp. I'm not a professional DBA, just a poor network tech who has to write a report in Visual Studio 2012 for the Sales dept., so please be kind.</p>
  
  <p>Basically, I need to write a query in the report designer that pulls from 2 tables - 'custextract' and 'histextract'. The result is 30 fields long (ALL of them needed in the report so I learned fast not to try and group in the query). </p>
  
  <p>The final report has to create a "Customer Contact Page" for sales people to take to the field - one page per customer. The top portion is basic customer information and comes entirely from the customer table, and the lower portion is a table of sales history information (period-to-date, year-to-date, last-year, etc.) by product line. There are about 30 possible product lines but most customers only buy from a few. The report should only return the TOP(10) rows for EACH Customer ORDERED BY year-to-date DESC - if that makes sense. The query I have so far is:</p>
  
  <pre><code>SELECT custextract.*, histextract.*
  FROM custextract 
  INNER JOIN histextract 
          ON custextract.[cusx-cust-no] = histextract.[hisx-cust]
  WHERE (custextract.[cusx-ecall-select] = 'Y')
  ORDER BY histextract.[hisx-sales-ytd] DESC
  </code></pre>
  
  <p>The obvious problem is that if I include TOP(10) in the SELECT, I get only the top 10 total, not per customer. I'm assuming I need to select a Count(histextract.[hisx-cust]) AS number and then do some kind of iterative loop based on number, joining all the results - but I'm totally lost how to effectively accomplish this. Select, From, Where, Order by, Into is basically the limits of my querying skill.</p>
  
  <p>I am populating those two tables from extracts of an ISAM database coming over as .csv files using a stored procedure (I still haven't figured out how to trigger it, but that's later). Basically just a TRUNCATE and BULK INSERT operation. But, if it would make sense to create a third table to hold sorted and filtered data and use that update procedure to continue on and create the desired dataset (then just use that third table in Report Designer) I'm open to it - just don't know how.</p>
  
  <p>Any help would be greatly appreciated.  </p>