[英]Insert a unique key, a couple of columns and the sum of sub-query into a table
我正在使用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
为tableA
的contributor_id
和project_id
的每个现有组合添加一个新行,如下所示
project_id
, tableA
project_id
contributor_user_id
,我需要tableA
contributor_id
pps
我需要在tableA
为其assigned_ppoints
state=2
contributor_user_id
和project_id
的assigned_ppoints
的总和 。 我的开始(也很遥远)是
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
一个组合。
我怎样才能做到这一点?
聚合过滤器 :
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
我建议这样的结构:
insert into A (...)
select
something_B,
another_B,
(select something_C from C where ...) as subselect_C
from B
where ...
;
如您所见,您将为B
每个匹配行执行子查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.