根据另一个 table 的数据集更改一个 table 的 LISTAGG 值

Change LISTAGG values from one table based on dataset from another table

我需要向注册活动的用户发送数据。当某个状态被删除或添加到与组关联的状态列表时,会发生这些事件。

一些上下文:我的数据有组,每个组都有一个状态列表,称为次级引导状态。小组可以有尽可能多或尽可能少的次要状态,因为他们 want/need。

所以第 1 组可以有 IA、WY 和 NY 作为次级领导,或者它可以只有 IA,或者它可以有 none。

我的问题涉及 3 个不同的 table。

这里是 table 的一些数据:

group_sublead_state

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

这个table告诉我们有两组,一组有两个副导联状态,一组有三个副导联状态

这是sublead_state_audittable

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

我们从审计中看到 table 最近的变化是

因此 sublead_change_results table 必须如下所示

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 列...这是我需要帮助的地方。

我必须使用这些 table 中的资源来编译 old_states 列中的逗号分隔列表。到目前为止,我的想法是尝试使用已经为 new_states 列构建的逻辑。因此,对于每个 group_id,我将从 current_states_list 中删除 sublead_state_audit table 的 state_added 列中的状态;我会将状态添加到 sublead_state_audit.

的 state_removed 列中的 current_states_list

LISTAGG 有可能吗?还有其他方法吗?任何帮助将不胜感激。

我认为这符合您的要求:

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;

Fiddle: http://sqlfiddle.com/#!4/2921e/1/0