有没有办法将选择查询的结果分成两个相等的一半?

Mat*_*ats 17 sql sql-server result-partitioning

我需要一个Sql Server 2005中的选择查询的解决方案.

我想让一个查询返回两个ResultSet,每个ResultSet中只有一半记录符合某个条件.我尝试将TOP 50 PERCENT与Order By结合使用但是如果表中的记录数是奇数,则两个结果集中都会显示一条记录.我不想在记录集上复制任何记录.例:

我有一个简单的表,其中包含TheID(PK)和TheValue字段(varchar(10))和5条记录.暂时跳过where子句.

SELECT TOP 50 PERCENT * FROM TheTable ORDER BY TheID asc
Run Code Online (Sandbox Code Playgroud)

得到所选id的1,2,3

SELECT TOP 50 PERCENT * FROM TheTable ORDER BY TheID desc
Run Code Online (Sandbox Code Playgroud)

得到所选id的3,4,5

3是复制品.在现实生活中,查询相当复杂,有大量的where子句和子查询.

ara*_*nid 41

SQL Server 2005及类似:

select *, ntile(2) over(order by theid) as tile_nr from thetable
Run Code Online (Sandbox Code Playgroud)

ntile(n)将输出分配给n个段,每个段具有相同的大小(当行数不能被n整除时给予或舍入).所以这会产生输出:

1 | value1 | 1
2 | value2 | 1
3 | value3 | 1
4 | value4 | 2
5 | value5 | 2
Run Code Online (Sandbox Code Playgroud)

如果您只想要上半部分或下半部分,则需要将其放入子查询中,例如:

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

将返回上半部分,同样x.tile_nr = 2用于下半部分

  • @KM - 是的,也在我的系统上测试过.假设是SQL2k5 +,这对我来说是最聪明的解决方案. (2认同)

Mar*_*ers 7

您可以使用以下两个查询:

SELECT * FROM (
    SELECT *, ROW_NUMBER() OVER (ORDER BY TheID) AS rn FROM TheTable
) T1
WHERE rn % 2 = 0

SELECT * FROM (
    SELECT *, ROW_NUMBER() OVER (ORDER BY TheID) AS rn FROM TheTable
) T1
WHERE rn % 2 = 1
Run Code Online (Sandbox Code Playgroud)