根据国外表中的日期和ID对COUNT进行分组

时间:2018-12-21 17:47:08

标签: mysql group-by

我需要获取同一结果集中由id_type和按天生成的报告计数。

我当前的查询显示了每种类型的报告总数,但也没有按天分开报告。

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_type = XX的值,但这不是达到我的要求的有效方法。

另一个重要要求是,如果在至少另一个id_type确实有报告的一天中没有来自id_type的报告,则结果计数应为零。

我用结构和一些示例数据创建了一个小提琴,其中id_type = 1应该有0个报告,id_type = 2应该有8个报告,而id_type = 3应该有5个报告。

http://sqlfiddle.com/#!9/6ceb48/2

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要与获取所有不同日期的子查询联接,然后将日期添加到分组中。

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

DEMO