从postgres中的2个表创建表

时间:2016-01-05 07:25:43

标签: postgresql recursive-query

表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表2:count = 2

Step1:占Rev = 10的50%

Step2:使用decay分配(除以2),所以10和5

    +-----+-------+
    | TID | Value |
    +-----+-------+
    | A   | 10    |
    | A   | 5     |
    | B   | 50    |
    | B   | 25    |
    | B   | 12.5  |
    | C   | 5     |
    | C   | 2.5   |
    +-----+-------+

1 个答案:

答案 0 :(得分:2)

设置:

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);

这是recursive 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)