MySQL Query GROUP BY day / month / year

前端 未结 14 2357
野趣味
野趣味 2020-11-22 06:37

Is it possible to make a simple query to count how many records I have in a determined period of time like a year, month, or day, having a TIMESTAMP field, like

相关标签:
14条回答
  • 2020-11-22 07:14

    If you want to get a monthly statistics with row counts per month of each year ordered by latest month, then try this:

    SELECT count(id),
          YEAR(record_date),
          MONTH(record_date) 
    FROM `table` 
    GROUP BY YEAR(record_date),
            MONTH(record_date) 
    ORDER BY YEAR(record_date) DESC,
            MONTH(record_date) DESC
    
    0 讨论(0)
  • 2020-11-22 07:14

    Here's one more approach. This uses [MySQL's LAST_DAY() function][1] to map each timestamp to its month. It also is capable of filtering by year with an efficient range-scan if there's an index on record_date.

      SELECT LAST_DAY(record_date) month_ending, COUNT(*) record_count
        FROM stats
       WHERE record_date >= '2000-01-01'
         AND record_date <  '2000-01-01' + INTERVAL 1 YEAR
       GROUP BY LAST_DAY(record_date) 
    

    If you want your results by day, use DATE(record_date) instead.

    If you want your results by calendar quarter, use YEAR(record_date), QUARTER(record_date).

    Here's a writeup. https://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/ [1]: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_last-day

    0 讨论(0)
提交回复
热议问题