私はpostgres DBを使用しています.DBの移行の途中で空のテーブルtableB
をデータから入力したい別のtableA
に存在する。ユニークなキーと2つのカラムとサブクエリの合計をテーブルに挿入
tableB
は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
が実際に外部キーを持っている次の列があります。 contributor_user_id
にtableA
project_id
に
- 、
project_id
を次のように私は
tableA
の既存の各contributor_id
の組み合わせとproject_id
ためtableB
上つの新しい行を追加する必要があり、Iは、tableA
の
- in
pps
私はの合計がassigned_ppoints
のcontributor_user_id
およびproject_id
であり、state=2
はtableA
である。
contributor_id
必要
マイ開始(と非常に遠い)のポイントが間違っている、とだけproject_id
とcontributor_id
の1つの組み合わせに対応する1行を追加します
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;
です。
どうすればいいですか?あなたは今、あなたがB
のすべての一致行のサブクエリにしてください見たよう
insert into A (...)
select
something_B,
another_B,
(select something_C from C where ...) as subselect_C
from B
where ...
;
:
それは完璧に動作しますが、私は INSERT INTO TABLEB(ID、PROJECT_ID、contributor_user_id、PPS)をしなければならなかった \tを選択 (SELECT MAX(ID)FROMテーブルB)AS maxId、 \t project_id、 \t contributor_id、 \t SUM(割り当て済みポイント)FILTER(WHERE状態= 2) FROM tableA GROUP BY project_id、contributor_id; –
(SELECT MAX(id)FROM tableB)がすべての新しい行に対して同じ値を返すので、すべてのIDが等しいという問題はあります。すべての手がかりは? –
@JoseOspina更新を確認してください –