MySQL Query with count and group by

Assuming that your date is an actual datetime column:

SELECT MONTH(date), YEAR(date), id_publisher, COUNT(*)
FROM raw_occurrence_record
GROUP BY MONTH(date), YEAR(date), id_publisher

You can concatenate your month & year like so:

SELECT CONCAT(MONTH(date), "https://stackoverflow.com/", YEAR(date)) AS Month, id_publisher, COUNT(*)
FROM raw_occurrence_record
GROUP BY MONTH(date), YEAR(date), id_publisher

To find months where there are no records, you will need a date table. If you can’t create one, you can UNION ALL a calendar table like so:

SELECT a.year, a.month, b.id_publisher, COUNT(b.id_publisher) AS num
FROM
  (SELECT 11 AS month, 2012 AS year
   UNION ALL
   SELECT 12, 2012
   UNION ALL
   SELECT 1, 2013
   UNION ALL
   SELECT 2, 2013) a
LEFT JOIN raw_occurence_record b
  ON YEAR(b.date) = a.year AND MONTH(b.date) = a.month
GROUP BY a.year, a.month, b.id_publisher

See a demo

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)