Mysql counts for every month.

I have a mysql table that looks like this:

id      level      time
1         1     2014-02-19 04:33:04
2         1     2014-03-19 04:33:04
3         1     2014-03-20 04:33:04
4         2     2014-03-21 04:53:04
5         1     2014-07-19 04:33:04
6         2     2014-07-19 04:33:04
7         1     2014-07-19 04:33:04
8         1     2014-08-19 04:33:04

I wanted to get results for level 1 as follows:

level1count    year    month
  0            2014      1
  1            2014      2
  2            2014      3
  0            2014      4
  0            2014      5
  0            2014      6
  2            2014      7
  1            2014      8
  0            2014      9
  0            2014      10
  0            2014      11
  0            2014      12

I tried this query but did not give a result for every month

SELECT YEAR(time) AS year, MONTH(time) AS month, COUNT(DISTINCT id) AS count FROM users where level = '1' GROUP BY year, month
+4
source share
2 answers

What you are looking for is to have all months as a result of whether they exist or do not exist in the database, for a set of results you need to have all months in a query like union, and then join your table over the years and for months

select coalesce(sum(`level` = 1),0) level1count
 coalesce(sum(`level` = 2),0) level2count ,y,m
from
(select 1 as m,2014 as y
union
.
.
.
union
select 12 as m ,2014 as y
) months
left join t on(months.m = month(t.time) and months.y = year(t.time))
group by months.m, year(t.time)

Demo

A better approach than joining is to have a table containing all your months over years, and then attach it to you with a table

+2
select sum(level = 1) as level1count, 
       year(`time`) as year, 
       month(`time`) as month
from your_table
group by year(`time`), month(`time`)
0

Source: https://habr.com/ru/post/1546595/


All Articles