在 postgres 中从 2 tables 创建 table

create table from 2 tables in postgres

Table 1:

+-----+-----+
| TID | Rev |
+-----+-----+
| A   |  20 |
| B   | 100 |
| C   |  10 |
+-----+-----+

Table 2:

+-----+-------+
| TID | Count |
+-----+-------+
| A   |     2 |
| B   |     3 |
| C   |     2 |
+-----+-------+

必填: 从 Table 1 中提取 50% 的转速,并根据 Table 中给定 TID 的计数使用线性衰减进行分配 2.

示例: 对于 TID=A,table1:Rev=20 Table2:count=2

步骤 1: 取 Rev = 10 的 50%

Step2: 使用衰减分布(除以 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);

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