我使用postgres,在DB迁移过程中,我有一个空表tableB
,我想从另一个tableA
中的数据中填充它。
tableB
有以下列
CREATE TABLE contributors (
id bigint NOT NULL,
pps double precision NOT NULL,
contributor_user_id bigint,
project_id bigint
);
而tableA
有以下列
CREATE TABLE tableA (
id bigint NOT NULL,
assigned_ppoints double precision NOT NULL,
state integer,
contributor_id bigint,
project_id bigint
);
所有的*_id
实际上都是外键。
我需要在tableB
上为contributor_id
和project_id
of tableA
的现有组合添加一个新行,如下所示
project_id
中,project_id
of tableA
contributor_user_id
,我需要contributor_id
of tableA
pps
中,我需要contributor_user_id
和project_id
的assigned_ppoints
和tableA
中的state=2
之和。我的起点(而且非常遥远)是
INSERT INTO tableB (id, project_id, contributor_user_id, pps)
SELECT MAX(id) FROM tableB, project_id, contributor_id, SUM(assigned_ppoints)
FROM tableA WHERE project_id=1 AND state=2 AND contributor_id=1;
这是错误的,并且只会添加与project_id
和contributor_id
的一个组合对应的一行。
我该怎么做?
发布于 2017-01-30 09:59:00
select
max(id),
contributor_id,
project_id,
sum(assigned_ppoints) filter (where state = 2)
from t
group by 2,3
9.3及以前的版本:
select
max(id),
contributor_id,
project_id,
sum(assigned_ppoints * (state = 2)::integer)
from t
group by 2,3
发布于 2017-01-30 09:00:30
我建议采用这样的结构:
insert into A (...)
select
something_B,
another_B,
(select something_C from C where ...) as subselect_C
from B
where ...
;
正如您现在看到的,您将对B
的每个匹配行执行子查询。
https://stackoverflow.com/questions/41941089
复制相似问题