gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:31:24 24 4
gpt4 key购买 nike

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

我希望有一个查询返回两个结果集,每个结果集恰好包含匹配特定条件的所有记录的一半。我尝试将 TOP 50 PERCENT 与 Order By 结合使用,但如果表中的记录数为奇数,则两个结果集中都会显示一条记录。我不想在记录集中重复任何记录。示例:

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

SELECT TOP 50 PERCENT * FROM TheTable ORDER BY TheID asc

结果为所选 ID 1,2,3

SELECT TOP 50 PERCENT * FROM TheTable ORDER BY TheID desc

结果为所选 ID 3,4,5

3 是重复的。当然,在现实生活中,查询相当复杂,有大量的 where 子句和子查询。

最佳答案

SQL Server 2005 及类似版本:

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

ntile(n) 将输出分配为 n 个段,每个段的大小相同(当行数不能被 n 整除时,进行四舍五入)。所以这会产生输出:

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

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

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

将返回上半部分,并类似地使用x.tile_nr = 2作为下半部分

关于sql - 有没有办法将选择查询的结果分成相等的两半?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2776006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com