0

TABLEA 包含数据,而 TABLEB 包含搜索条件

这是一个包含数据的 SQL Fiddle

  1. TABLEA
    visited_states_time
    AL= Alabama,2, AK=Alaska,5
    AR=Arkansas,6
    AZ=Arizona,10
    CA=California, 10,CT=Connecticut,20
    
    TABLEB
    CRITERIA
    AL
    HI
    CA
    CT
    AK
    
  2. 期望的结果

    visited_states ...................................     total_time_spent
    AL= Alabama, AK=Alaska ............................     7
    CA=California, CT=Connecticut...................        30
    
4

1 回答 1

1

这是一个糟糕的数据模型。你也没有说条件tableb。如果有任何状态匹配,或者如果全部匹配?

因为我们需要将行拆分(到 sum())然后重新组合它们,您可以使用:

SQL> with v as (select rownum r,
  2                    ','||visited_states_time||',' visited_states_time,
  3                    length(
  4                      regexp_replace(visited_states_time, '[^,]', '')
  5                    )+1 fields
  6               from tablea)
  7  select trim(both ',' from visited_states_time) visited_states_time,
  8         sum(total_time_spent) total_time_spent
  9    from (select *
 10            from v
 11                 model
 12                 partition by (r)
 13                 dimension by (0 as f)
 14                 measures (visited_states_time, cast('' as varchar2(2)) state,
 15                           0 as total_time_spent, fields)
 16                 rules (
 17                   state[for f from 0 to fields[0]-1  increment 2]
 18                     = trim(
 19                        substr(visited_states_time[0],
 20                               instr(visited_states_time[0], ',', 1, cv(f)+1)+1,
 21                               instr(visited_states_time[0], '=', 1, (cv(f)/2)+1)
 22                               - instr(visited_states_time[0], ',', 1,  cv(f)+1)-1
 23                              )),
 24                   visited_states_time[any]= visited_states_time[0],
 25                   total_time_spent[any]
 26                      = substr(visited_states_time[0],
 27                               instr(visited_states_time[0], ',', 1, (cv(f)+2))+1,
 28                               instr(visited_states_time[0], ',', 1,  (cv(f)+3))
 29                               - instr(visited_states_time[0], ',', 1,  (cv(f)+2))-1
 30                             )
 31                 ))
 32   where state in (select criteria from tableb)
 33   group by visited_states_time;

VISITED_STATES_TIME                   TOTAL_TIME_SPENT
------------------------------------- ----------------
CA=California, 10,CT=Connecticut,20                 30
AL=Alabama,2, AK=Alaska,5                            7

但说真的,重写该数据模型以将它们分开存储。

于 2013-01-11T12:29:27.450 回答