简体   繁体   English

将一个唯一键,几列和子查询的总和插入表中

[英]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 我需要在tableBtableAcontributor_idproject_id的每个现有组合添加一个新行,如下所示

  • in project_id , project_id of tableA project_idtableA project_id
  • in contributor_user_id , I need contributor_id of tableA contributor_user_id ,我需要tableA contributor_id
  • in 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_idproject_idassigned_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_idcontributor_id一个组合。

How can I do this? 我怎样才能做到这一点?

Aggregate filter : 聚合过滤器

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM