Sql 在表中插入一个唯一键、两列和子查询的总和 我使用PoxGRESDB,在DB迁移的中间,我有一个空表Table,我想从另一个表中存在的数据中填充。< /P>

Sql 在表中插入一个唯一键、两列和子查询的总和 我使用PoxGRESDB,在DB迁移的中间,我有一个空表Table,我想从另一个表中存在的数据中填充。< /P>,sql,postgresql,Sql,Postgresql,表B有以下列 CREATE TABLE contributors ( id bigint NOT NULL, pps double precision NOT NULL, contributor_user_id bigint, project_id bigint ); CREATE TABLE tableA ( id bigint NOT NULL, assigned_ppoints double precision NOT NULL,

表B有以下列

CREATE TABLE contributors (
    id bigint NOT NULL,
    pps double precision NOT NULL,
    contributor_user_id bigint,
    project_id bigint
);
CREATE TABLE tableA (
    id bigint NOT NULL,
    assigned_ppoints double precision NOT NULL,
    state integer,
    contributor_id bigint,
    project_id bigint
);
而tableA有以下几列

CREATE TABLE contributors (
    id bigint NOT NULL,
    pps double precision NOT NULL,
    contributor_user_id bigint,
    project_id bigint
);
CREATE TABLE tableA (
    id bigint NOT NULL,
    assigned_ppoints double precision NOT NULL,
    state integer,
    contributor_id bigint,
    project_id bigint
);
所有*_id实际上都是外键

我需要在tableB上为tableA的参与者id和项目id的每个现有组合添加一行,如下所示

在project_id中,表A的project_id 在contributor\u user\u id中,我需要tableA的contributor\u id 在pps中,我需要表A中状态为2的参与者用户id和项目id的分配点数之和。 我的出发点是非常遥远的

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;
这是错误的,只会添加一行对应于项目id和参与者id的一个组合


我该怎么做

我建议这样的结构:

insert into A (...)
select
  something_B,
  another_B,
  (select something_C from C where ...) as subselect_C
from B
where ...
;
正如您现在看到的,您将对B的每个匹配行执行子查询。

对于9.3和以前的版本:

select
    max(id),
    contributor_id,
    project_id,
    sum(assigned_ppoints * (state = 2)::integer)
from t
group by 2,3

它工作得很好,我必须插入到tableB id,project\u id,contributor\u user\u id,pps选择从tableB中选择MAXid作为MAXid,project\u id,contributor\u id,sumsassigned\u ppoints过滤器,其中state=2从tableA组按项目\u id,contributor\u id;我仍然存在一个问题,即SELECT MAXid FROM tableB为所有新行返回相同的值,因此所有ID都相等。有什么线索吗?我还有一个问题,新表上的id必须是唯一的。我已经解决了这个问题,创建了一个新的序列并使用了nextval的“tableB_seq”。