postgres 改变 table 并插入行概率
postgres alter table and insert row probabilities
我想对具有相同 id1 的行的权重求和,然后计算列概率中每一行的比率(有点像概率)。
Table数据:
id1 weight id2
1 0.1 3
1 0.2 4
1 0.3 5
1 0.8 6
2 0.5 7
2 0.6 8
2 0.7 9
输出应该是:
id1 weight id2 prob
1 0.1 3 0.07
1 0.2 4 0.1429
1 0.3 5 0.214
1 0.8 6 0.5714
2 0.5 7 0.2778
2 0.6 8 0.3333
2 0.7 9 0.3388
试试这个
SELECT t.*,t.wieght/t1.Weight AS Prob FROM TABLE_NAME t INNER JOIN
(
SELECT id1,SUM(weight) AS Weight FROM TABLE_NAME GROUP BY id1
)t1 ON t.id = t1.id
使用相关子select对一个id的所有权重求和:
select id1, weight, id2,
weight / (select sum(weight) from table t2 where t2.id = t1.id) as prob
from table t1
尝试一下;
select
t.id1, t.weight, t.id2, (t.weight/t1.tot) prob
from tbl t
join (
select id1, sum(weight) tot
from tbl
group by id1
) t1
on t.id1 = t1.id1
这可以通过 window 函数轻松解决,该函数通常比任何使用子查询或派生 table:
的解决方案更快
select id1,
weight,
id2,
weight / sum(weight) over (partition by id1) as prob
from items
order by id1, id2;
SQLFiddle 示例:http://sqlfiddle.com/#!15/64453/1
我想对具有相同 id1 的行的权重求和,然后计算列概率中每一行的比率(有点像概率)。
Table数据:
id1 weight id2
1 0.1 3
1 0.2 4
1 0.3 5
1 0.8 6
2 0.5 7
2 0.6 8
2 0.7 9
输出应该是:
id1 weight id2 prob
1 0.1 3 0.07
1 0.2 4 0.1429
1 0.3 5 0.214
1 0.8 6 0.5714
2 0.5 7 0.2778
2 0.6 8 0.3333
2 0.7 9 0.3388
试试这个
SELECT t.*,t.wieght/t1.Weight AS Prob FROM TABLE_NAME t INNER JOIN
(
SELECT id1,SUM(weight) AS Weight FROM TABLE_NAME GROUP BY id1
)t1 ON t.id = t1.id
使用相关子select对一个id的所有权重求和:
select id1, weight, id2,
weight / (select sum(weight) from table t2 where t2.id = t1.id) as prob
from table t1
尝试一下;
select
t.id1, t.weight, t.id2, (t.weight/t1.tot) prob
from tbl t
join (
select id1, sum(weight) tot
from tbl
group by id1
) t1
on t.id1 = t1.id1
这可以通过 window 函数轻松解决,该函数通常比任何使用子查询或派生 table:
的解决方案更快select id1,
weight,
id2,
weight / sum(weight) over (partition by id1) as prob
from items
order by id1, id2;
SQLFiddle 示例:http://sqlfiddle.com/#!15/64453/1