fab*_*vys 3 sql postgresql math window-functions threshold
我有一个表t1的postgresql数据库,我想计算一个阈值.阈值应该是例如汽车1使用的燃料比所有汽车的75%多,car2使用的燃料比所有汽车的50%多,....数学上我理解我想做什么,但我不知道如何建造询问
id | name | value | threshold
________________________
1 | car1 | 30 | ...%
2 | car2 | 15 | ..%
3 | car3 | 7 |
4 | car4 | 5 |
Run Code Online (Sandbox Code Playgroud)
这是一个sql小提琴 http://sqlfiddle.com/#!15/1e914/1
UPDATE t1
SET threshold =
select count(value)
from t1
Run Code Online (Sandbox Code Playgroud)
where(value> [在每一行]),然后是*100 /总计数()
对不起那个糟糕的尝试,但我有点迷茫.还尝试了一些聚合函数.
您可以通过窗口功能非常优雅地解决这个问题:
UPDATE t1
SET threshold = sub.thr
FROM (
SELECT id, 100. * (rank() OVER (ORDER BY value) - 1) / count(*) OVER () AS thr
FROM t1) sub
WHERE t1.id = sub.id;
Run Code Online (Sandbox Code Playgroud)
该rank()函数给出了有序集中的等级(从1开始),在这种情况下,在列上value,然后除以集合中的总行数.请注意,count(*) OVER ()计算该分区中的总行数,但它不像常规count(*)那样聚合行.