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

后端 未结 6 1751
无人及你
无人及你 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:42

    If this is SQL Server 2000, then I'd be inclined to find the PK of the middle value like so:

    Declare @MiddleId int
    
    Set @MiddleId = (
                    Select TOP 1 PK
                    From (
                            Select TOP 50 PERCENT PK
                            From Table
                            Order By TheId ASC
                            )
                    Order By TheId DESC
                    )
    
    Select ...
    From Table
    Where TheId <= @MiddleId
    
    Select ..
    From Table
    Where TheId > @MiddleId
    

    With SQL Server 2005, I'd be inclined to do the same but you can use a CTE

    ;With NumProjects As
        (
        Select Id, ROW_NUMBER() OVER (ORDER BY TheId ASC ) As Num
        From Table
        )
    Select @MiddleId = Id
    From Table
    Where Num = CEILING( (Select Count(*) From Table) / 2 )
    

提交回复
热议问题