[英]ORACLE SQL Query Table using criteria from other table
TABLEA contains the data, while TABLEB contains the search criteria TABLEA包含数据,而TABLEB包含搜索条件
Here is a SQL Fiddle with the data 这是一个带有数据的SQL Fiddle
Tables 桌子
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
Desired Result 所需结果
visited_states ................................... total_time_spent AL= Alabama, AK=Alaska ............................ 7 CA=California, CT=Connecticut................... 30
That's a terrible data model. 那是一个糟糕的数据模型。 also you didn't say the condition for tableb
. 你也没有说tableb
的条件。 if any state matches, or if all? 是否有任何状态匹配,或者全部匹配?
as we need to split the rows up (to sum()) and then recombine them you can use: 因为我们需要将行拆分(以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
but seriously, rewrite that data model to store them separately to start with. 但是请认真地重写该数据模型,以从头开始单独存储它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.