簡體   English   中英

將一個唯一鍵,幾列和子查詢的總和插入表中

[英]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實際上都是外鍵。

我需要在tableBtableAcontributor_idproject_id的每個現有組合添加一個新行,如下所示

  • project_idtableA project_id
  • contributor_user_id ,我需要tableA contributor_id
  • pps我需要在tableA為其assigned_ppoints state=2 contributor_user_idproject_idassigned_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_idcontributor_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM