Mysql 按日期和外部表id分组计数

Mysql 按日期和外部表id分组计数,mysql,group-by,Mysql,Group By,我需要获得同一结果集中按id_类型和按天生成的报告数 我当前的查询显示每种类型的总报告,但也不按天分隔报告 SELECT DATE(report.date_insert) AS date_insert, type.name, count(report.id_type) as number_of_orders from type left join report on (type.id_type = report.id_type) group by type.id_type 如您所见,它们之间唯

我需要获得同一结果集中按id_类型和按天生成的报告数

我当前的查询显示每种类型的总报告,但也不按天分隔报告

SELECT DATE(report.date_insert) AS date_insert, type.name, count(report.id_type) as number_of_orders
from type
left join report
on (type.id_type = report.id_type)
group by type.id_type
如您所见,它们之间唯一的区别是我更改了
type.id\u type=XX
的值,但这不是实现我的要求的有效方法

另一个重要的要求是,如果在一天中没有来自至少另一个
id\u类型
有报告的
id\u类型的报告,那么应该有一个计数为零的结果

我已经创建了一个结构和一些示例数据,其中id_type=1应该有0个报告,id_type=2应该有8个报告,id_type=3应该有5个报告


谢谢

您需要加入一个子查询,该子查询获取所有不同的日期,然后将该日期添加到分组中

SELECT alldates.date_insert, type.name, IFNULL(COUNT(report.id_type), 0) AS number_of_orders
FROM (
    SELECT DISTINCT DATE(date_insert) AS date_insert
    FROM report) AS alldates
CROSS JOIN type
LEFT JOIN report ON type.id_type = report.id_type AND alldates.date_insert = DATE(report.date_insert)
GROUP BY alldates.date_insert, type.id_type
ORDER BY alldates.date_insert, type.name