ORACLE SQL查询表使用其他表中的条件

时间:2013-01-11 10:38:25

标签: sql string oracle

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

这是SQL Fiddle with the data

  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
    

1 个答案:

答案 0 :(得分: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

但严重的是,重写该数据模型以单独存储它们。