sqloracle-databasegroup-bycountoracle9i

Group data by part of string in oracle sql ( Oracle9i Enterprise Edition Release 9.2.0.4.0)


I have the following query:

select referrer, count(distinct ad_id) as Adverts,
       sum(case f when 'Y' then hits else 0 end) as clicks,
       sum(case f when 'N' then hits else 0 end) as views
from advert_view_hits
where ad_id in ({$id_strings})
group by referrer"

This will return data like the following:

 Referrer  Adverts  Clicks  Views
 Caterer     3       124     74
 Indeed      5       234     136

Which is fine but some cases the referrer has been stored in the db like this:

user1@jwrecruitment.co.uk_200890,
user2@jwrecruitment.co.uk_200890

user1@gatewayjobs.co.uk_200890, 
user3@towngate-personnel.co.uk_2

How would I go about grouping the data based on just the company of the user emails that have been used as the referrer.

so the data would look like this:

Referrer             Adverts  Clicks  Views
 Caterer               3       124     74
 Indeed                5       234     136
 jwrecruitment.co.uk   8       456     782 
 gatewayjobs.co.uk     9       897     959

So that all data for an emails like jwrecruitment.co.uk would be grouped together and displayed.


Solution

  • You can also use the regexp_substr to find the string between @ and _ as follows:

    select REGEXP_SUBSTR(referrer,'@([^_]+)',1,1,NULL,1) referrer, 
           count(distinct ad_id) as Adverts,
           sum(case f when 'Y' then hits else 0 end) as clicks,
           sum(case f when 'N' then hits else 0 end) as views
      from advert_view_hits
    where ad_id in ({$id_strings})
    group by REGEXP_SUBSTR(referrer,'@([^_]+)',1,1,NULL,1)
    

    If you are on older version then instead of regexp_substr use the combination of the SUBSTR and INSTR as follows:

    SUBSTR(referrer, 
           INSTR(referrer, '@') + 1, 
           DECODE(INSTR(referrer, '_', - 1), 
                  0, 
                  LENGTH(referrer) - INSTR(referrer, '@'), 
                  INSTR(referrer, '_', - 1) - INSTR(referrer, '@') - 1)
          )