【问题标题】:Confused between inner join and left join- Building report in sql对内连接和左连接感到困惑-在sql中构建报告
【发布时间】:2020-12-29 11:27:22
【问题描述】:

表格:

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

所需的输出:

我的部分代码:

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

输出:

  1. Views_report
select date(v.created_at) "created_at", c.customer_name, 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';

输出:

我被困在哪里:

  • 如何将我的第一个代码与第二个代码组合,然后将结果表与我的第三个代码组合起来以得到所需的输出。如果这种方法不好。请提出更好的方法。 请务必编写代码。

【问题讨论】:

  • use text, not images/links, for text--including tables & ERDs。仅将图像用于无法表达为文本或增强文本的内容。在图像中包含图例/键和说明。阅读代码和引用的编辑帮助重新块格式。给报价单。请不要大喊。不要要求我们编写您的代码。 How to Askhelp center
  • 请在代码问题中给出minimal reproducible example--cut & paste & runnable code,包括最小的代表性示例输入作为代码;期望和实际输出(包括逐字错误消息);标签和版本;明确的规范和解释。给出您可以给出的最少代码,即您显示的代码可以通过您显示的代码扩展为不正常。 (调试基础。)对于包含 DBMS 和 DDL(包括约束和索引)和输入为格式化为表的代码的 SQL。 How to Ask 展示你能做什么并解释卡住的地方。

标签: mysql join subquery left-join inner-join


【解决方案1】:

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, customer_id, 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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    相关资源
    最近更新 更多