mysql - 返回整个月的行数,即使该月可能没有条目。返回 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);
解决方案
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;
推荐阅读
- node.js - Gitlab 测试覆盖率可视化不起作用
- flutter - Flutter DevTools 打开一个空白屏幕
- python - 我正在尝试创建产品并保存到数据库但不工作
- python - 我们如何创建输入栅格的掩码版本,其中落入其中一个字段的像素设置为 ` & 其他为 0?
- xml - URI urn:this-stylesheet 不识别外部 Java 类
- unit-testing - 即使使用 null 返回函数,CakePHP 单元测试也会返回不完整、跳过或有风险的测试
- javascript - 当我在 daterangepicker 上触发更改事件时未触发其他 ID
- html - Chrome中的自动填充错误?
- flutter - 升高的按钮高度不增加
- c# - 将文件内容附加到现有文件