2015-06-30 106 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

相关问题