2015-06-30 105 views
0

我需要向註冊事件的用戶發送數據。這些事件發生在狀態被刪除或添加到與組相關的狀態列表中時。根據另一個表中的數據集更改一個表中的LISTAGG值

某些上下文:我的數據有組,並且每個組都有一個狀態列表,稱爲分攤狀態。團體可以擁有他們想要/需要的亞裔國家。

因此,第1組可以有IA,WY和NY作爲亞分類,或者它可以只有IA,或者它可以沒有。

我的問題涉及3個不同的表格。

  • 表稱爲group_sublead_state保持條目屬於一個組
  • 審計表稱爲sublead_state_audit保持當一個sublead狀態被添加或從一組
  • 表稱爲除去的信息的每個sublead狀態sublead_change_results當他們訂閱的狀態從用戶電子郵件中出現時,會從組轉移或添加到組轉移狀態列表(此表應該是我的查詢結果,我不能創建此表,插入,刪除,或更新。這嚴格來說是一個長而醜陋的選擇查詢的結果,這個查詢將另外兩個表以及co持有類似組名稱等(其他表不相關))

這裏有一些數據表中的其他信息表uple:

group_sublead_state

group_id state 
1   IA 
1   WY 
2   NY 
2   OH 
2   NV 

此表告訴我們有是兩個團體,一個有兩個轉會國家,一個有三個轉會國家

這裏是sublead_state_audit表

group_id state_added state_removed 
1   none   MO 
1   IA    none 
2   NY    none 
2   OH    none 
2   none   CA 

我們從審覈表中看到,最近的變化是

  • GROUP_ID 1例MO刪除,IA增加
  • GROUP_ID 2有紐約和OH增加,以及CA刪除

所以sublead_change_results表必須像下面

group_id old_states new_states 
1   MO,WY   IA,WY 
2   CA,NV   NY,OH,NV 

因此,new_states列非常簡單,我已經使用LISTAGG函數完成了它(我們將爲每個組current_state_list調用該列表)。 old_states專欄雖然...這是我需要幫助的地方。

我必須使用這些表中的資源來編譯old_states列中的逗號分隔列表。到目前爲止,我的想法是嘗試使用爲new_states列創建的邏輯。因此,對於每個group_id,我將從current_states_list中刪除位於sublead_state_audit表的state_added列中的狀態;我會將狀態添加到位於sublead_state_audit的state_removed列中的current_states_list

這是否儘可能與LISTAGG?有另一種方法可以做到嗎?任何幫助將不勝感激。

回答

0

我想這你想要做什麼:

select x.group_id, 
     x.old_states, 
     y.new_states 
    from (select group_id, 
       listagg(state, ',') within group(order by state) as old_states 
      from (select group_id, 
         state_removed as state 
        from sublead_state_audit 
       where state_removed <> 'none' 
       union all 
       select group_id, 
         state 
        from group_sublead_state 
       where state not in (select state_added from sublead_state_audit)) 
     group by group_id) x 
    join (select group_id, 
       listagg(state, ',') within group(order by state) as new_states 
      from group_sublead_state 
     group by group_id) y 
    on x.group_id = y.group_id; 

小提琴:http://sqlfiddle.com/#!4/2921e/1/0

+0

我相信你解決我的問題!正在努力檢查出來。一旦完成,將此標記爲解決方案。 – Simoney

相關問題