问题描述
问题:使用这些表格,生成一个表格,显示2020年3月(包括周末)的每一天和客户(入职日期或之后的每一天)的活跃用户数在产品上(查看建筑物或创建注释),总共查看了多少建筑物,总共创建了多少注释。请注意,即使客户当天未活跃,也应出现。
所需的输出:
我的部分代码:
- Notes_report
select date(n.created_at) "created_at",c.customer_name,count(n.user_id) "total_notes",count(distinct n.user_id) "active_user"
from customer c left join notes n on c.customer_id=n.customer_id
group by customer_name,date(created_at);
输出:
- Views_report
select date(v.created_at) "created_at",count(v.user_id) "total_views",count(distinct v.user_id) "active_user"
from customer c left join building_views v on c.customer_id=v.customer_id
group by customer_name,date(created_at);
输出:
3)日期和客户名称:
select d.date,c.customer_name
from date_spine d left join customer c on d.date>=c.onboarding_date
where d.date between '2020-03-01' and '2020-03-31';
输出:
我困在哪里:
解决方法
添加LEFT JOIN
以及从其他每个表中获取所需计数的子查询。
select d.date,c.customer_name,IFNULL(n.total_notes,0) total_notes,IFNULL(n.active_user,0) active_user,IFNULL(v.total_views,0) total_views
from date_spine d
left join customer c on d.date>=c.onboarding_date
left join (
select date(n.created_at) date,customer_id,count(*) total_notes,count(distinct n.user_id) active_user
from notes
group by customer_id,date
) AS n ON n.customer_id = c.customer_id AND n.date = d.date
LEFT JOIN (
select date(v.created_at) date,count(*) total_views
from building_views v
group by customer_id,date
) AS v ON v.customer_id = c.customer_id AND v.date = d.date
where d.date between '2020-03-01' and '2020-03-31'
子查询不需要与customer
联接,因为只有主查询才需要这样做以获得名称。子查询仅使用客户ID。