如何编写 SQL 查询以从 table 中提取 50% 的记录?

How to write SQL query for extracting 50 percent of records from a table?

如何在 ANSI SQL 中检索 50% 的记录。在 MS SQL 服务器中,我们有 Top 百分比。但是我想进入 Oracle 和 PostgreSQL.

在 Postgres 中,一个选项使用 percent_rank()。假设 id 是您的排序列:

select *
from (select t.*, percent_rank() over(order by id) prn from mytable t) t
where prn <= 0.5

这也适用于 Oracle,但对于该数据库,我更喜欢 fetch 子句:

select *
from mytable t
order by id
fetch first 50 percent rows only