我正在尝试使用公用表表达式在 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/