2017-03-06 84 views
-1

我需要編寫一個postgres查詢來獲取beta_plan_id的集羣ID,稍後再做一些操作。對於下表中的單個beta_plan_id,可能會有許多商品編號和很多CLUSTER_ID。這將如何處理?需要關於postgres代碼的for循環的建議

BETA_PLAN_ID MERCH_LEVEL1_ID BETA_PLAN_MERCH_LVL1_CLSTR_ID NO_OF_STORES 
1     1     12       5,6,7 
1     1     13       9,10 
1     1     14       2,3,4 
2     2     15       13,12 

SELECT BETA_PLAN_MERCH_LVL1_CLSTR_ID INTO i_clstr_id 
FROM beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR 
WHERE BETA_PLAN_ID = in_beta_plan_id; 

問題是許多結果將被返回,因爲BETA_PLAN_MERCH_LVL1_CLSTR_ID是串行類型和(beta_plan_id,merch_id,CLUSTER_ID)組合唯一地生成的。

SELECT BETA_PLAN_MERCH_LVL1_CLSTR_ID 
    INTO i_clstr_id 
    FROM beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR 
    WHERE BETA_PLAN_ID = in_beta_plan_id; 

INSERT INTO beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR 
    (
     BETA_PLAN_ID, 
     MERCH_LEVEL1_ID, 
     CLUSTER_ID, 
     CLUSTER_NAME, 
     NO_OF_STORES, 
     NO_OF_FOOTAGE_VARIATION, 
     CREATED_USER, 
     CREATED_TS 
    ) 
    SELECT 
     out_plan_id, 
     merch_lvl1_clstr.MERCH_LEVEL1_ID, 
     merch_lvl1_clstr.CLUSTER_ID, 
     merch_lvl1_clstr.CLUSTER_NAME, 
     merch_lvl1_clstr.NO_OF_STORES, 
     merch_lvl1_clstr.NO_OF_FOOTAGE_VARIATION 
     in_user_id, 
     now() 
    FROM beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR merch_lvl1_clstr 
     INNER JOIN beta_plan.BETA_PLAN_MERCH_COPY_PLAN merch_copy 
     ON merch_copy.MERCH_ID = merch_lvl1_clstr.MERCH_LEVEL1_ID 
      AND merch_lvl1_clstr.BETA_PLAN_ID = in_beta_plan_id 
    RETURNING BETA_PLAN_MERCH_LVL1_CLSTR_ID INTO o_clstr_id; 

INSERT INTO beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR_STR 
    (
     BETA_PLAN_MERCH_LVL1_CLSTR_ID, 
     STORE_ID, 
     CREATED_USER, 
     CREATED_TS   
    ) 
    SELECT 
     o_clstr_id, 
     STORE_ID,  
     in_user_id, 
     now() 
    FROM beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR_STR 
    WHERE BETA_PLAN_MERCH_LVL1_CLSTR_ID = i_clstr_id; 
+0

您要爲給定的「BETA_PLAN_ID」返回哪個「BETA_PLAN_MERCH_LVL1_CLSTR_ID」? –

+0

我需要行beta_plan_id 1有cluster_id的12,13,14 ..我需要在clstr_str表中插入這些id和相應的store_id的上面。所以基本上我需要一個選擇語句循環通過記錄並插入clstr_str表最後。 –

+0

在PostgreSQL函數或數據庫客戶端的編程語言中? –

回答

0

代替第一SELECT語句,使用FOR環包圍中的其他語句:

FOR i_clstr_id IN 
    SELECT BETA_PLAN_MERCH_LVL1_CLSTR_ID 
    FROM beta_plan.BETA_PLAN_MERCH_LVL1_CLSTR 
    WHERE BETA_PLAN_ID = in_beta_plan_id 
LOOP 
    /* your two INSERT statements come here */ 
END LOOP; 

詳見the documentation