2013-01-11 31 views
0

TABLEA包含的數據,而TABLEB包含搜索條件ORACLE SQL查詢表使用標準從其他表

這裏是一個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 
    
+10

正常化您的數據,疼痛就會消失。 –

+0

您的sql小提琴中的數據與您上面發佈的內容不符。 – Taryn

回答

1

這是一個可怕的數據模型。你也沒有說tableb的條件。如果任何狀態匹配,或者全部匹配?

因爲我們需要了分裂行(總結()),然後重新組合它們,你可以使用:

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 

但嚴重的是,重寫數據模型要分別儲存開始。

+0

用MODEL子句敲擊他們!這將教會他們使​​用適當的數據結構! – APC