postgresql - 无法让 Percentile_Cont() 在 Postgresql 中工作

标签 postgresql

我正在尝试使用公用表表达式在 PostgreSQL 中使用 percentile_cont() 函数来计算百分位数。目标是找到账户余额的前 1%(此处称为金额)。我的逻辑是找到第 99 个百分位数,这将返回那些账户余额大于 99% 的同行(从而找到第 1 个百分位数)

这是我的问题

--ranking subquery works fine
with ranking as(
       select a.lname,sum(c.amount) as networth  from customer a
       inner join 
       account b on a.customerid=b.customerid
       inner join 
       transaction c on b.accountid=c.accountid 
       group by a.lname order by sum(c.amount)
 )
select lname, networth, percentile_cont(0.99) within group 
order by networth over (partition by lname) from ranking ;

我一直收到以下错误。

ERROR:  syntax error at or near "order"
LINE 2: ...ame, networth, percentile_cont(0.99) within group order by n..

我在想,也许我忘记了右大括号等,但我似乎无法弄清楚在哪里。我知道这可能与 order 关键字有关,但我不确定该怎么做。你能帮我解决这个错误吗?

最佳答案

这也把我绊倒了。

事实证明 percentile_cont 在 postgres 9.3 中不支持,仅在 9.4+ 中支持。

https://www.postgresql.org/docs/9.4/static/release-9-4.html

所以你必须使用这样的东西:

with ordered_purchases as (
  select
      price,
      row_number() over (order by price) as row_id,
      (select count(1) from purchases) as ct
  from purchases
)

select avg(price) as median
from ordered_purchases
where row_id between ct/2.0 and ct/2.0 + 1

查询关心https://www.periscopedata.com/blog/medians-in-sql (部分:“Postgres 的中位数”)

关于postgresql - 无法让 Percentile_Cont() 在 Postgresql 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42168045/

相关文章:

sql - 如何使用 SQL 查询更改顺序

postgresql - nginx/node.js/postgres 是一个非常可扩展的架构吗?

postgresql - Postgres 和 Atlassian Jira : driver issue

postgresql - ActiveRecord::StatementInvalid: PG::DataCorrupted: 错误

postgresql - 初始化数据库 : error: program "postgres" is needed by initdb but was not found using circleci ubuntu docker-compose docker-entrypoint-initdb. d

postgresql - TypeORM 中的 Postgres 枚举

sql - SQL 新手 - 无法获取季度日期输出

PostgreSQL 内置索引与手动创建索引 : Performance aspect

database - 将数据库转储加载到 postgres 数据库中

bash - 在 Postgres 日志记录机制中更改定界符和换行符