我正在使用postgres数据库,并且在数据库迁移过程中,我有一个空表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
和tableA
project_id
的每个现有组合添加一个新行,如下所示
project_id
,tableA
contributor_user_id
contributor_id
中,我需要tableA
pps
assigned_ppoints
我需要contributor_user_id
project_id
的{em>总和 state=2
tableA
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
和{{1}}的一个组合。
我该怎么做?
答案 0 :(得分:2)
Sys.info()
sysname release version nodename
"Windows" ">= 8 x64" "build 9200" "DESKTOP-G88LPOJ"
machine login user effective_user
"x86-64" "franc" "franc" "franc"
对于9.3及以前的版本:
select
max(id),
contributor_id,
project_id,
sum(assigned_ppoints) filter (where state = 2)
from t
group by 2,3
答案 1 :(得分:1)
我建议这样的结构:
insert into A (...)
select
something_B,
another_B,
(select something_C from C where ...) as subselect_C
from B
where ...
;
如您所见,您为B
的每个匹配行执行子查询。