SQL:使用CASE将一个表中的记录与另一个表中的计数连接起来

时间:2019-06-17 11:13:35

标签: sql postgresql

我是SQL的新手,因此需要这个聪明的社区的帮助。 我有两个表-table1,其中包含page_idtable2的列表,其中包含referral_url的多个记录,其中包含每个page_id的记录以及更多记录。

表1:

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

表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
   ...      | .....

所需的结果应类似于:

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

我没有运气尝试过这个

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;

有人可以提出解决方案吗?表2是巨大的,因此我想避免在那里做CASE

1 个答案:

答案 0 :(得分:3)

您的查询过于复杂。这应该做您想要的:

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;