首页 > 解决方案 > 返回整个月的行数,即使该月可能没有条目。返回 0 表示月/天,没有条目

问题描述

即使一个月没有条目,我也在尝试获取月份计数。我查看了几个示例,但未能使其发挥作用。我有一个 3 表如下

$tablename="约会"

时间输入 地位
2020-10-25 13:00:00 完全的
2020-11-25 13:00:00 完全的
2020-12-25 13:00:00 完全的

通过使用以下 select 语句,我可以得到每个月的以下计数:

select MONTHNAME(timeIn),Count(*) from ".$tablename." WHERE timeIn!=:null group by MONTHNAME(timeIn) order by MONTHNAME(timeIn) DESC"

{十月:“1”,十一月:“1”,十二月:“1”}

通过在线搜索,我发现了这个选择,我已经对其进行了修改以与我的表一起使用。它不起作用,我不确定这有什么问题,因为我不熟悉 mysql。

SELECT  Months.id AS `month` , COUNT(`".$tablename."`.timeIn) AS `count` FROM (SELECT 'January' as ID UNION SELECT 'February' as ID UNION  SELECT 'March' as ID UNION SELECT 'April' as ID UNION SELECT 'May' as ID UNION SELECT 'June' as ID UNION SELECT 'July' as ID UNION SELECT 'August' as ID UNION SELECT 'September' as ID UNION SELECT 'October' as ID UNION SELECT 'November' as ID UNION SELECT 'December' as ID) as Months LEFT JOIN `".$tablename."` on Months.id=monthname(`".$tablename."`.timeIn) AND (status = 'Completed') GROUP BY Months.

我想得到如下结果,如果该月没有条目,它将返回 0。请能够提供一些解释,因为理解 mysql 语句有点挑战性。感谢我能得到的任何帮助

{一月:“0”,.....,十一月:“0”,十月:“1”,十一月:“1”,十二月:“1”}

来自 AKINA 答案的更新

$sql="SELECT MONTHNAME(CONCAT('2020-', cte.num, '-1')) `Month`, COUNT(".$tablename.".timeIn) `Count` FROM (SELECT 1 NUM UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) cte LEFT JOIN ".$tablename." ON cte.num = MONTH(".$tablename.".timeIn) GROUP BY 1;";
$data=$con->prepare($sql);
$data->execute();
$rows=$data->fetchAll(PDO::FETCH_ASSOC);

标签: mysqlcount

解决方案


WITH RECURSIVE
cte AS ( SELECT 1 num
         UNION ALL
         SELECT num + 1 FROM cte WHERE num < 12 )
SELECT MONTHNAME(CONCAT('2020-', cte.num, '-1')) `Month`, 
       COUNT(appointments.timeIn) `Count`
FROM cte
LEFT JOIN appointments ON cte.num = MONTH(appointments.timeIn)
GROUP BY 1;

小提琴

PS。需要 MySQL 8。


使用版本 5.6.32 – Ahsan

SELECT MONTHNAME(CONCAT('2020-', cte.num, '-1')) `Month`, COUNT(appointments.timeIn) `Count`
FROM (SELECT 1 NUM UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION 
      SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION 
      SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) cte
LEFT JOIN appointments ON cte.num = MONTH(appointments.timeIn)
GROUP BY 1;

小提琴


推荐阅读