我有一个像这样的主表
customer_id Customer_name
1 A
2 B
3 C
4 D
我有多个用户活动表。我只给出了2个这样的表的例子,但是有20个这样的表
表1:
customer_id activity_date No_of_likes
2 1/1/16 2
3 1/1/16 3
2 2/1/16 5
2 1/1/16 1
表2:
customer_id activity_date No_of_comments
2 1/1/16 1
4 5/1/16 7
2 6/1/16 2
这是我需要的最后一张桌子。我没有主日历表,我不确定如何加入以获得以下输出
customer_id activity_name activity_date quantity
1 - - -
2 Likes 1/1/16 3
2 Likes 2/1/16 5
2 Comments 1/1/16 1
2 Comments 6/1/16 2
3 Likes 1/1/16 3
4 Comments 5/1/16 7
我还需要这样的输出。我认为合并解决了上述问题,但我不知道如何做到以下
customer_id activity_date like_quantity comment_activity
1 - - -
2 1/1/16 3 1
2 2/1/16 5 -
2 6/1/16 - 2
3 1/1/16 3 -
4 5/1/16 - 7
希望我很清楚。请帮助我查询有关此连接的SQL查询
答案 0 :(得分:1)
你可以试试这个:
使用UNION
和LEFT JOIN
即可完成此任务。
SELECT
your_master_table.customer_id,
COALESCE(t.activity_name,'-') AS activity_name,
COALESCE(t.activity_date,'-') AS activity_date,
COALESCE(t.quantity,'-') AS quantity
FROM your_master_table
LEFT JOIN
(
SELECT
customer_id,
activity_date,
No_of_likes AS quantity,
'Likes' AS activity_name
FROM TABLE_1
UNION
SELECT
customer_id,
activity_date,
No_of_comments AS quantity,
'Comments' AS activity_name
FROM TABLE_2
) AS t
ON your_master_table.customer_id = t.customer_id
ORDER BY your_master_table.customer_id;
在您的示例输入上运行上述查询,您将获得以下输出:
<强>输出强>:
| customer_id | activity_name | activity_date | quantity |
|-------------|---------------|---------------|----------|
| 1 | - | - | - |
| 2 | Comments | 2016-01-01 | 1 |
| 2 | Comments | 2016-01-06 | 2 |
| 2 | Likes | 2016-01-01 | 2 |
| 2 | Likes | 2016-01-02 | 5 |
| 2 | Likes | 2016-01-01 | 1 |
| 3 | Likes | 2016-01-01 | 3 |
| 4 | Comments | 2016-01-05 | 7 |
修改强>
根据您的要求变更
SELECT
your_master_table.customer_id,
COALESCE(DATE_FORMAT(t.activity_date,'%d/%m/%y'),'-') AS activity_date,
COALESCE(SUM(CASE WHEN t.activity_name = 'Likes' THEN t.quantity END),'-') AS like_quantity,
COALESCE(SUM(CASE WHEN t.activity_name = 'Comments' THEN t.quantity END),'-') AS comment_activity
FROM your_master_table
LEFT JOIN
(
SELECT
customer_id,
activity_date,
No_of_likes AS quantity,
'Likes' AS activity_name
FROM TABLE_1
UNION
SELECT
customer_id,
activity_date,
No_of_comments AS quantity,
'Comments' AS activity_name
FROM TABLE_2
) AS t
ON your_master_table.customer_id = t.customer_id
GROUP BY your_master_table.customer_id,t.activity_date
ORDER BY your_master_table.customer_id;