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: 
You can use the NTILE(100) function along with a over clause partition by section to get 

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

```

should be

```
declare @limit int = 10;

;with data as (
   SELECT NTILE(100) over (partition by sectionid ORDER BY NEWID() ) as Centile, [Id], [Question] 
   FROM [Questions] 
   WHERE [SectionId] IN (1,2)
)
select * from data where centile <= @limit

```

<https://learn.microsoft.com/en-us/sql/t-sql/functions/ntile-transact-sql>
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()

```