[英]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.