[英]Insert a unique key, a couple of columns and the sum of sub-query into a table
I am using postgres DB and, in the middle of a DB migration, I have an empty table tableB
which I want to fill from data existing in another tableA
. 我正在使用postgres DB,在数据库迁移过程中,我有一个空表tableB
,我想从另一个tableA
存在的数据中填充。
tableB
has the following columns tableB
具有以下列
CREATE TABLE contributors (
id bigint NOT NULL,
pps double precision NOT NULL,
contributor_user_id bigint,
project_id bigint
);
while tableA
has the following columns 而tableA
有以下列
CREATE TABLE tableA (
id bigint NOT NULL,
assigned_ppoints double precision NOT NULL,
state integer,
contributor_id bigint,
project_id bigint
);
All *_id
are actually foreign keys. 所有*_id
实际上都是外键。
I need to add one new row on tableB
for each existing combination of contributor_id
and project_id
of tableA
as follows 我需要在tableB
为tableA
的contributor_id
和project_id
的每个现有组合添加一个新行,如下所示
project_id
, project_id
of tableA
在project_id
, tableA
project_id
contributor_user_id
, I need contributor_id
of tableA
在contributor_user_id
,我需要tableA
contributor_id
pps
i need the sum of assigned_ppoints
of that contributor_user_id
and project_id
for which state=2
within tableA
. 在pps
我需要在tableA
为其assigned_ppoints
state=2
contributor_user_id
和project_id
的assigned_ppoints
的总和 。 My starting (and very distant) point is 我的开始(也很遥远)是
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;
Which is wrong, and would only add one row corresponding to one combination of project_id
and contributor_id
. 这是错误的,只会添加一行对应于project_id
和contributor_id
一个组合。
How can I do this? 我怎样才能做到这一点?
select
max(id),
contributor_id,
project_id,
sum(assigned_ppoints) filter (where state = 2)
from t
group by 2,3
For 9.3 and previous versions: 对于9.3及以前的版本:
select
max(id),
contributor_id,
project_id,
sum(assigned_ppoints * (state = 2)::integer)
from t
group by 2,3
I'd suggest a structure like this: 我建议这样的结构:
insert into A (...)
select
something_B,
another_B,
(select something_C from C where ...) as subselect_C
from B
where ...
;
As you see now you'd do a subquery for every matching row of B
. 如您所见,您将为B
每个匹配行执行子查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.