aviss
aviss

Reputation: 2439

SQL: Join records in one table with count from another using CASE

I'm new to SQL so need help of this smart community. I have two tables - table1 with a list of page_id and table2 which contains multiple records of referral_url for each of these page_id and many more.

Table1:

page_id | views
-----------------
0       |234
2       |567
9       |890
1       |123

Table 2:

    page_id | referral_url
    ---------------------------
    0       |link.facebook.com
    1       |link.google.com
    0       |link.facebook.com
    3       |link.instagram.com
    1       |link.twitter.com
   ...      | .....

The desired result should look like:

page_id | views  | social | search 
-----------------------------------
0       |234     | 2      | 0
2       |567     | 4      | 2  
9       |890     | 6      | 0
1       |123     | 0      | 1

I tried this with no luck:

SELECT A.page_id, B.referrer
FROM table1 A
LEFT JOIN (
SELECT page_id,

COUNT(
CASE
        WHEN referrer_url LIKE '%%facebook%%'
        OR referrer_url LIKE '%%instagram%%' 
        OR referrer_url LIKE '%%twitter%%' 
            THEN 'social' 
END) AS social,

COUNT(
CASE
        WHEN referrer_url LIKE '%%google%%'
        OR referrer_url LIKE '%%bing%%' 
        OR referrer_url LIKE '%%yahoo%%' 
            THEN 'search' 
END) AS search

FROM table2
WHERE dt BETWEEN '20190401' AND '20190430') B 
ON B.page_id = A.page_id
GROUP BY A.page_id, B.social, B.search;

Could anyone suggest a solution? Table 2 is HUGE so I wanted to avoid doing CASE there.

Upvotes: 1

Views: 52

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269563

Your query is over-complicated. This should do what you want:

SELECT A.page_id, A.views,
       SUM(CASE WHEN referrer_url LIKE '%%facebook%%' OR
                     referrer_url LIKE '%%instagram%%' OR
                     referrer_url LIKE '%%twitter%%' 
                THEN 1 ELSE 0
           END) AS social,
       SUM(CASE WHEN referrer_url LIKE '%%google%%' OR
                     referrer_url LIKE '%%bing%%' OR
                     referrer_url LIKE '%%yahoo%%' 
                THEN 1 ELSE 0
           END) AS search
FROM table1 A LEFT JOIN
     table2 B
     ON B.page_id = A.page_id   
WHERE B.dt BETWEEN '20190401' AND '20190430'
GROUP BY A.page_id, A.views;

Upvotes: 3

Related Questions