Is there a way to split the results of a select query into two equal halfs?

后端 未结 6 1727
无人及你
无人及你 2020-12-28 17:19

I need a solution for a select query in Sql Server 2005.

I\'d like to have a query returning two ResultSets each of which holding exactly half of all records matchin

6条回答
  •  执念已碎
    2020-12-28 17:47

    SQL Server 2005 and similar:

    select *, ntile(2) over(order by theid) as tile_nr from thetable
    

    ntile(n) allocates the output into n segments, each of the same size (give or take rounding when the number of rows isn't divisible by n). So this produces the output:

    1 | value1 | 1
    2 | value2 | 1
    3 | value3 | 1
    4 | value4 | 2
    5 | value5 | 2
    

    If you just want the top or bottom half, you need to put this into a subquery, e.g.:

    select theid, thevalue from (
      select theid, thevalue, ntile(2) over(order by theid) as tile_nr from thetable
    ) x
    where x.tile_nr = 1
    

    will return the top half, and similarly use x.tile_nr = 2 for the bottom half

提交回复
热议问题