如何计算每年每月甚至一个月的行数不存在

时间:2016-01-04 16:52:02

标签: php mysql

我试图计算每年每个月的行数(在表格中有几年),而不是跳过空月。说我的桌子有一个月没有数据。像1,2,5,6,7,11,12(缺少3,4,8,9,10)。但是我不希望输出跳过它 - 只是改为0。

我想出了这段代码,但它跳过了空记录。

SELECT
    YEAR(`log_datetime`) as year,MONTH(`log_datetime`) AS mon,
    count(log_id) AS count
FROM
    log_db
GROUP BY
    MONTH (`log_datetime`),
    YEAR (`log_datetime`)
ORDER BY
    YEAR (`log_datetime`) DESC,
    MONTH (`log_datetime`) DESC

我的期望是:

+------+----+-----+
| 2015 | 12 | 100 |
+------+----+-----+
| 2015 | 11 | 120 |
+------+----+-----+
| 2015 | 10 |  0  |
+------+----+-----+
| 2015 | 09 |  0  |
+------+----+-----+
| 2015 | 08 |  0  |
+------+----+-----+
| 2015 | 07 | 123 |
+------+----+-----+
| 2015 | 06 | 200 |
+------+----+-----+
| 2015 | 05 | 250 |
+------+----+-----+
| 2015 | 04 |  0  |
+------+----+-----+
| 2015 | 03 |  0  |
+------+----+-----+
| 2015 | 02 | 211 |
+------+----+-----+
| 2015 | 01 | 200 |
+------+----+-----+

2 个答案:

答案 0 :(得分:1)

您需要calendar表来执行此操作。

SELECT c.years,
       c.months, 
       Count(log_id) AS count 
FROM   calendar_table C 
       LEFT OUTER JOIN log_db l 
                    ON c.months = Month (`log_datetime`) 
                       AND c.years = Year (`log_datetime`) 
GROUP  BY c.years, 
          c.months 
ORDER  BY c.months DESC, 
          c.years DESC 

请参阅以下链接以生成日历表

  1. How to populate a table with a range of dates?
  2. https://www.brianshowalter.com/calendar_tables
  3. https://gist.github.com/bryhal/4129042

答案 1 :(得分:0)

创建一个日历表,并使用log_db表进行左连接。