使用 MySQL GROUP BY 表达式计数时如何包含零

发布于 2024-11-09 15:44:46 字数 634 浏览 0 评论 0原文

我想统计上个月每天发生的事件数,但如果未找到任何事件,也将计数为零。这可能吗?

这就是我从...开始的内容...

SELECT COUNT(*) AS count, 
DATE(usage_time_local) AS d 
FROM usages 
WHERE user_id=136 
AND DATE(usage_time_local) >= DATE('2011-04-24') 
AND DATE(usage_time_local) <= DATE('2011-05-24') 
GROUP BY DATE(usage_time_local);

更新:给出答案,我通过初始化循环然后填写详细信息来实现代码解决方案。

  $dailyCount = array();
  for( $i=1; $i<=30; $i++ ) {
      $day = date('Y-m-d',(time()-($i*24*60*60)));
      $dailyCount[$day] = 0;
  }
  foreach( $statement as $row ) {
    $dailyCount[$row['d']] = $row['count'];
  }

I'd like to count the number events that occur on each day over the last month, but also include a count of zero when no events are found. Is that possible?

Here's what I'm starting from...

SELECT COUNT(*) AS count, 
DATE(usage_time_local) AS d 
FROM usages 
WHERE user_id=136 
AND DATE(usage_time_local) >= DATE('2011-04-24') 
AND DATE(usage_time_local) <= DATE('2011-05-24') 
GROUP BY DATE(usage_time_local);

UPDATE: Given the answer, I implemented a code solution by initializing a loop and then filling in the details.

  $dailyCount = array();
  for( $i=1; $i<=30; $i++ ) {
      $day = date('Y-m-d',(time()-($i*24*60*60)));
      $dailyCount[$day] = 0;
  }
  foreach( $statement as $row ) {
    $dailyCount[$row['d']] = $row['count'];
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

摇划花蜜的午后 2024-11-16 15:44:46

您无法使用标准 SQL 查询来执行此操作 - 您将尝试对表中不存在的日期进行分组。

标准解决方法是创建一个临时表,其中按顺序无间隙地包含日期范围,将其与表连接并像往常一样进行计数/聚合。

You can't do this with standard SQL queries - you'd be trying to group on a date(s) that doesn't exist in the table.

Standard workaround is to make a temporary table that contains the date range in sequential order with no gaps, join that against your table and do the count/aggregate as usual.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文