表 1:
+-----+-----+
| TID | Rev |
+-----+-----+
| A | 20 |
| B | 100 |
| C | 10 |
+-----+-----+
表 2:
+-----+-------+
| TID | Count |
+-----+-------+
| A | 2 |
| B | 3 |
| C | 2 |
+-----+-------+
必需: 从表 1 中取出 50% 的转速,并根据表 2 中给定 TID 的计数使用线性衰减进行分配。
示例:对于 TID=A,table1:Rev=20 Table2:count=2
第一步:取 Rev = 10 的 50%
第二步:使用衰减分布(除以2),所以10和5
+-----+-------+
| TID | Value |
+-----+-------+
| A | 10 |
| A | 5 |
| B | 50 |
| B | 25 |
| B | 12.5 |
| C | 5 |
| C | 2.5 |
+-----+-------+
最佳答案
设置:
create table revs (tid text, rev numeric);
insert into revs values
('A', 20),
('B', 100),
('C', 10);
create table counts (tid text, ct int);
insert into counts values
('A', 2),
('B', 5),
('C', 2);
这是递归 cte
的情况:
with recursive revrec(tid, rev, ct) as (
select tid, rev / 2, ct- 1
from revs
join counts using(tid)
union
select tid, rev / 2, ct- 1
from revrec
where ct > 0
)
select tid, rev
from revrec
order by tid, ct desc;
tid | rev
-----+---------------------
A | 10.0000000000000000
A | 5.0000000000000000
B | 50.0000000000000000
B | 25.0000000000000000
B | 12.5000000000000000
B | 6.2500000000000000
B | 3.1250000000000000
C | 5.0000000000000000
C | 2.5000000000000000
(9 rows)
关于postgresql - 从 postgres 中的 2 个表创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34606264/