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

时间:2017-01-30 16:43:46

标签: sql postgresql

我正在使用postgres数据库,并且在数据库迁移过程中,我有一个空表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实际上都是外键。

我需要在contributor_id上为project_idtableA project_id的每个现有组合添加一个新行,如下所示

  • 位于project_idtableA contributor_user_id
  • contributor_id中,我需要tableA
  • pps
  • assigned_ppoints我需要contributor_user_id project_id的{​​em>总和 state=2 tableA 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和{{1}}的一个组合。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

Aggregate filter

Sys.info()
      sysname           release           version          nodename 
    "Windows"        ">= 8 x64"      "build 9200" "DESKTOP-G88LPOJ" 
      machine             login              user    effective_user 
     "x86-64"           "franc"           "franc"           "franc" 

对于9.3及以前的版本:

select
    max(id),
    contributor_id,
    project_id,
    sum(assigned_ppoints) filter (where state = 2)
from t
group by 2,3

答案 1 :(得分:1)

我建议这样的结构:

insert into A (...)
select
  something_B,
  another_B,
  (select something_C from C where ...) as subselect_C
from B
where ...
;

如您所见,您为B的每个匹配行执行子查询。