I asked a question here: Identify phone numbers in a PL/SQL iteration
and I got a perfect answer, but now I need to use this in a complex select statement.
The goal is the same result in a column joined to a query. For example:
SELECT t1.phone_number
, t2.origin_country
, sum(t1.volume) Total_vol
, sum(t1.charge) Total_chg
from t2
LEFT JOIN t1 ON t1.item_no = t2.item_no
LEFT JOIN t3 ON t3.vcode = t2.vcode
LEFT JOIN /*<<Here should be a subquery which attach the column with
the countries to my query>>*/
+many WHERE and GROUP BY clauses
The problem is the number of the columns and source tables can vary, therefore I am looking for a flexible solution I can use with any complex query where a phone_number column exists. What I have already tried:
put the entire select into a loop and join to
SELECT ic.country FROM int_codes ic WHERE ic.int_code = substr(t1.phone_number, 1, i)
as a subquery, but it can't work obviously because it's not stored, no fields to fill
create a view in a procedure and join the countries to it, but it's not flexible
- not tried but thought about a script with many UNION and NOT EXISTS, but it would be incredibly complicated and slow to run
- with CURSOR but the error message said I had to define a TYPE on schema level, but it's still not flexible due to a determined table structure.
So how should I do this?
(If anybody has a totally different approach to identify and display phone numbers in a table flexibly they are welcome)
--UPDATE--
The solution:
select ... PHONE_NUMBER, XY, ZZ, ... ,
case
when i.INT_CODE = substr(PHONE_NUMBER,1,4) then i.COUNTRY
when i.INT_CODE = substr(PHONE_NUMBER,1,3)
and i.INT_CODE = substr(PHONE_NUMBER,1,4) then i.COUNTRY
when i.INT_CODE = substr(PHONE_NUMBER,1,2)
and i.INT_CODE = substr(PHONE_NUMBER,1,3) then i.COUNTRY
when i.INT_CODE = substr(PHONE_NUMBER,1,1)
and i.INT_CODE = substr(PHONE_NUMBER,1,2) then i.COUNTRY
else 'Unidentified location'
end TARGET_COUNTRY
from (
select ... t1.phone_number ,sum(xy) Total XY, sum(zz) ZZ, ...
/*same fields like in the main query above*/
left join t2 on ...
left join t3 on ...
where date = 'some date' and country in ('country1','country2') ...
/*many conditions*/
group by t2.phone_number,
t3.account ...
) MainQuery
left join int_codes i
on ( i.INT_CODE = substr(MainQuery.PHONE_NUMBER, 1, 1)
or i.INT_CODE = substr(MainQuery.PHONE_NUMBER, 1, 2)
or i.INT_CODE = substr(MainQuery.PHONE_NUMBER, 1, 3)
or i.INT_CODE = substr(MainQuery.PHONE_NUMBER, 1, 4)
);