简体   繁体   中英

How to count rows each month of each year even a month is not present

I'm trying to count the rows of each month of each year (there're a few years in a table) without skipping the empty month. Saying my table has some month without the data in it. Like 1,2,5,6,7,11,12 (3,4,8,9,10 is missing). But I don't want the output skip it - just put 0 instead.

I come up with this code but it skipping the empty record.

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

What I expect is:

+------+----+-----+
| 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 |
+------+----+-----+

You need a calendar table to do this.

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 

Refer the below links to generate calendar table

  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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM