2017-01-30 9 views
3

私はpostgres DBを使用しています.DBの移行の途中で空のテーブルtableBをデータから入力したい別のtableAに存在する。ユニークなキーと2つのカラムとサブクエリの合計をテーブルに挿入

tableBtableAしばらく

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_idtableA

  • project_id

    • project_idを次のように

      私はtableAの既存の各contributor_idの組み合わせとproject_idためtableB上つの新しい行を追加する必要があり、Iは、tableA

    • contributor_id必要
    • in pps私はの合計assigned_ppointscontributor_user_idおよびproject_idであり、state=2tableAである。

    マイ開始(と非常に遠い)のポイントが間違っている、とだけproject_idcontributor_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 ... 
    ; 
    

  • 答えて

    2

    Aggregate filter:9.3および以前のバージョンの

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

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

    それは完璧に動作しますが、私は 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; –

    +0

    (SELECT MAX(id)FROM tableB)がすべての新しい行に対して同じ値を返すので、すべてのIDが等しいという問題はあります。すべての手がかりは? –

    +0

    @JoseOspina更新を確認してください –

    1

    私はこのような構造をお勧めしたいです。

    関連する問題