Skip to content
Advertisement

Is there a way of getting a proportional section of an SQL table?

I’m trying to split a single query into 4 parts, for readability purposes.

Having it as a single query, while adequate, isn’t “pretty” for display purposes.

An example would be a query that brings in something akin to the below.

Column1Number Column2Text
001 Desc1
100 Desc100

And what I would like it to be able to bring in, is the above, but split into 4 (or X) equal parts.

Column1Number Column2Text
001 Desc1
25 Desc25
Column1Number Column2Text
26 Desc26
50 Desc50
Column1Number Column2Text
51 Desc51
75 Desc75
Column1Number Column2Text
76 Desc76
100 Desc100

The above 4 tables could then be displayed next to each other horizontally.

There will be “other” filters on the WHERE clause but it will result in a list of numbers and their corresponding text. Think product number and product description for an example.

What I think I need is a method of dividing the MAX(Column1Number) by 4 and putting that result into a variable. Perhaps something along these lines.

From there, I should be able to “quarter” the variables

Finally, some relatively simple adjustments to the 4 SQL queries.

I think the above will work with contiguous numbers. i.e. a continuous count of 1 to 100 but will break if some numbers are missing, or the list doesn’t start at 1. By break, I mean the 4 queries won’t be equal in length.

I will be able to have the same set of variables in 4 separate queries, and custom setting the WHERE clause is also not an issue. It probably won’t be efficient, but that isn’t much of a concern at the moment.

In the end. I’m hoping there is some trick to this.

All help is appreciated.

Advertisement

Answer

For this you could use NTILE. NTILE is T-SQL’s way of dividing rows as evenly as possible.

Returns:

Note that the performance of NTILE is not spectacular. For better performance you can use an NTally Table as this is the fastest method for evenly dividing rows; far more performance than NTILE. There’s a little more work required though.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement