【问题标题】:How to write SQL query for extracting 50 percent of records from a table?如何编写 SQL 查询以从表中提取 50% 的记录?
【发布时间】:2021-01-04 05:28:04
【问题描述】:

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

【问题讨论】:

  • 您是否愿意添加 1) 表结构 2) 示例数据和 3) 预期结果?
  • @Jim Jones,这是一个通用问题。我认为不需要样本数据,表结构。

标签: oracle postgresql sql-order-by greatest-n-per-group sql-limit


【解决方案1】:

在 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

【讨论】:

  • 附带说明:在内部,fetch first 50 percent 被转换为 select * from (select row_number() over (order by id) as rn, count(*) over () as total) where rn &lt;= (total * 50/100)
  • @GMB ,您的查询正在运行。你能帮我,如何在数据仓库中编写相同的查询。
  • 为什么不能在数据仓库中使用相同的查询?
  • @thatjeffsmith,此关键字在 Hive 等数据仓库中不可用。
  • 关键字在所有 sql 中都不是通用的,如 oracle、MS sql、postgresql 等,我正在研究 hive,但面临复制相同的问题。
猜你喜欢
  • 2021-12-14
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 2015-10-27
  • 1970-01-01
  • 2021-09-18
  • 2022-09-24
相关资源
最近更新 更多