Q:

How to find Min and Max values of equal sized bins using SQL query

I have a table with 2 columns. { UserId, Date}. This table has says N rows and I want to break them into  bins of size M rows each so a total of N/M bins. UserId and Date can be repeated over multiple rows in the table. Each bin should have non-overlapping user ids in sequential order.
for ex: if table has 100 rows and each bin should have size 25 then the bin ranges are as follows
bin 1: User 1 - User 20 ( 25 rows)
bin 2 : User 21 - User 80 (25 rows)
bin 3: User 81 - User 95 (25 rows)
bin 4: User 96 - User 100 (25 rows)
How can I write a SQL query to get these bin ranges?

A:

It sounds to me like you're looking for the NTILE function: http://msdn.microsoft.com/en-us/library/ms175126.aspx
In this case, the select part query might look like SELECT UserId, NTILE(4) OVER (ORDER BY UserId ASC) AS Bin FROM ...
You would modify the number 4 beside NTILE above based on how many bins you want.
This will give you the "Bin" number for each row, which you can then use to group however you wish.

