【问题标题】:group by and count(*) after join加入后分组和计数(*)
【发布时间】:2020-09-08 16:18:34
【问题描述】:

以下代码将一个充满日期的表与一个在“X”日期有注册表的表连接起来。

SELECT
  d.date as 'fecha',
  IFNULL(q.name,0) as 'nombre'
FROM dates d
LEFT JOIN quarantine_registry q
ON d.date = q.change_date where d.date <= CURDATE() order by d.date desc

输出类似于:

fecha - nombre

2020-09-08 - 0  
2020-09-07 - ggg
2020-09-07 - dwdw  
2020-09-07 - test  
2020-09-07 - Uuu  
2020-09-07 - aaaacdac  
2020-09-07 - asaaws  
2020-09-07 - dwdwdw  
2020-09-07 - vsed  
2020-09-07 - ppp  
2020-09-07 - test  
2020-09-07 - Ygg  
2020-09-07 - Cc  
2020-09-07 - 0      
... 

我忘了:我只想加入quarantine_registry中change_type = 'add'的注册表

如何计算每个日期拥有的注册表数量并按日期分组?

感谢您的宝贵时间

【问题讨论】:

  • 加入后使用GROUP BYCOUNT(),就像你在标题中说的那样。
  • 我忘了:我只想加入quarantine_registry中change_type = 'add'的注册表
  • 将其添加到ON 条件:ON d.date = q.change_date AND q.change_type = 'add'

标签: mysql sql datetime count left-join


【解决方案1】:
SELECT d.date AS 'fecha',
       count(id) AS registeries_count
FROM dates d
LEFT JOIN quarantine_registry q ON d.date = q.change_date
WHERE d.date <= CURDATE()
GROUP BY d.date
ORDER BY d.date DESC

【讨论】:

    【解决方案2】:

    如何计算每个日期拥有的注册表数量并按日期分组?

    你似乎想要聚合:

    select d.date, count(q.change_date) cnt
    from dates d
    left join quarantine_registry q on d.date = q.change_date 
    where d.date <= current_date
    group by d.date
    

    基本上,查询从日期表开始,并尝试带入相应的注册表行。然后数据集按日期分组,我们计算在注册表中找到了多少行(如果没有匹配的行,则计数为0)。

    【讨论】:

    • 我忘了:我只想加入quarantine_registry中change_type = 'add'的注册表
    • @ÒscarFuentes:只需将该条件添加到left join,例如:... left join quarantine_registry q on d.date = q.change_date and q.change_type = 'add'
    【解决方案3】:

    我猜 null 不算数

    SELECT
      d.date as 'fecha',
      count(*)
    FROM dates d
    LEFT JOIN quarantine_registry q
    ON d.date = q.change_date where d.date <= CURDATE()
    where q.name is not null
    group by d.date
    order by d.date desc
    

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多