简体   繁体   English

MySQL查询与计数和分组

[英]MySQL Query with count and group by

I've got table a table with different records for publishers, each record have a date in a column of type timestamp. 我已经为发布者创建了一个表,该表具有不同的记录,每个记录在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.

I need a count for number of records published by each publisher for each month. 我需要计算每个发布者每个月发布的记录数。 For example 例如

Month    |  id_publisher         | num
11/2012  |          1            |   1
11/2012  |          2            |   0
11/2012  |          3            |   0
11/2012  |          4            |   1
.....
02/2013  |          4            |   2

I tried with select count(id) from raw_occurrence_record group by month(date), id_publisher; 我尝试select count(id) from raw_occurrence_record group by month(date), id_publisher;

but, it did not work. 但是,它没有用。

Assuming that your date is an actual datetime column: 假设您的日期是实际的datetime列:

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), '/', 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: 如果您无法创建一个日历表,则可以将UNION ALL日历表都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

See a demo 观看演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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