繁体   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