内部联接和左联接之间混淆-SQL中的生成报告

问题描述

表格:

enter image description here

问题:使用这些表格,生成一个表格,显示2020年3月(包括周末)的每一天和客户(入职日期或之后的每一天)的活跃用户数在产品上(查看建筑物或创建注释),总共查看了多少建筑物,总共创建了多少注释。请注意,即使客户当天未活跃,也应出现。

所需的输出

enter image description here

我的部分代码

  1. 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);  

输出

enter image description here

  1. 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);

输出

enter image description here

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';

输出

enter image description here

我困在哪里:

解决方法

添加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。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...