Question: I have a table that persists a lot of questions, each question belongs to a section:

```
Id      Question        SectionId
 1      What is ...     3
 2      Who is...       3
 3      When is...      2
 4      Why is...       1
 5      How is...       3

```

There is like 1000 questions, and around 50 sections. However, my query is simple, I select a given number of questions from the table from specific sections, for example

```
SELECT TOP 10 [Id], [Question] FROM [Questions] 
WHERE [SectionId] IN (1,2)
ORDER BY NEWID()

```

This is simple and working fine, except that sometimes I get 5 questions out of the requested 10 from a section that has only 6 questions, and 2 from a section that has 100 questions, and 3 from a section that has 20 questions. 

How can I make the result "proportional" with the number of the questions in each section. For example if I request 10 questions, I get more questions from the section that has more questions, and less questions from the sections with less questions. 

The only I can think of currently is to make multiple queries, first one to get the number of questions in each section, then do some math and decide how many questions from each section, and then make another few queries to get the number of questions as I want. This sound intensive and I hope there's a more practical way.

Note: An SQL query, or EF Linq query would work.

Answer: 
For a stratified sample, do an nth sample on the ordering. This is a little tricky, but this should work:

```
SELECT TOP (10) q.*
FROM (SELECT q.*,
             ROW_NUMBER() OVER (ORDER BY section, NEWID()) as seqnum,
             COUNT(*) OVER (ORDER BY section, NEWID()) as cnt
      FROM [Questions] q
      WHERE [SectionId] IN (1, 2)
     ) q
ORDER BY seqnum % (cnt / 10);

```

There may be some boundary conditions on this logic, but as the number of questions grows and the sample is large enough, it should do what you want.
You could select always 10% of your records in any sections with this:

```
SELECT TOP ( select CAST(( COUNT(*) * 0.1 ) AS INT ) 
FROM QUESTION WHERE SECTIONID IN ( 1,2)) * FROM QUESTION 
WHERE [SectionId] IN (1,2)
ORDER BY NEWID()

```