带有count和group by的MySQL Query

use*_*933 28 mysql group-by count

我为表提供了一个表,其中包含不同的发布者记录,每个记录都有一个类型为timestamp的列中的日期.

id | id_publisher | date
1           1      11/2012 03:09:40 p.m.
2           1      12/2012 03:09:40 p.m.
3           2      01/2013 03:09:40 p.m.
4           3      01/2013 03:09:40 p.m.
5           4      11/2012 03:09:40 p.m.
6           4      02/2013 03:09:40 p.m.
7           4      02/2012 03:09:40 p.m.
Run Code Online (Sandbox Code Playgroud)

我需要计算每个发布者每个月发布的记录数量.例如

Month    |  id_publisher         | num
11/2012  |          1            |   1
11/2012  |          2            |   0
11/2012  |          3            |   0
11/2012  |          4            |   1
.....
02/2013  |          4            |   2
Run Code Online (Sandbox Code Playgroud)

我尝试使用raw_occurrence_record group by month(date)中的select count(id),id_publisher;

但是,不要工作.

Ker*_*mit 38

假设您的日期是实际datetime列:

SELECT MONTH(date), YEAR(date), id_publisher, COUNT(*)
FROM raw_occurrence_record
GROUP BY MONTH(date), YEAR(date), id_publisher
Run Code Online (Sandbox Code Playgroud)

您可以像这样连接您的月份和年份:

SELECT CONCAT(MONTH(date), '/', YEAR(date)) AS Month, id_publisher, COUNT(*)
FROM raw_occurrence_record
GROUP BY MONTH(date), YEAR(date), id_publisher
Run Code Online (Sandbox Code Playgroud)

要查找没有记录的月份,您需要一个日期表.如果你不能创建一个,你可以UNION ALL像这样的日历表:

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
Run Code Online (Sandbox Code Playgroud)

看演示