MySQL statement - select max from the group

Hi, I have the following table and I want to select max (count (*)) to connect to each month. sqlfiddle.com/#!2/13036/1

select * from broadcast

profile, plugged, company, tstamp
1,       2,       1,       2013-10-01 08:20:00
1,       3,       1,       2013-10-01 08:20:00
2,       1,       1,       2013-10-01 08:20:00
2,       3,       1,       2013-10-01 08:20:00
3,       1,       1,       2013-10-01 08:20:00
3,       1,       1,       2013-09-01 08:20:00

so if I do something like the following:

    select plugged, 
           count(*), 
           extract(month from tstamp), 
           extract(year from tstamp) 
      from broadcast 
     where company=1
  group by plugged, 
           extract(month from tstamp), 
           extract(year from tstamp)
  order by count(*) desc;

exit:

plugged, count(*), extract(month from tstamp), extract(year from tstamp)
3,       2,        10,                         2013
1,       2,        10,                         2013
2,       1,        10,                         2013
1,       1,        9,                          2013

desired result:

plugged, count(*), extract(month from tstamp), extract(year from tstamp)
3,       2,        10,                         2013
1,       2,        10,                         2013
1,       1,        9,                          2013

which is right ... but I only need max (count (*)) (for example, the first line only in this case). There may be scenarios in which there are 2 rows with a maximum number, but for each month / year I want to return only rows with a maximum score ... do I need an internal select statement or something else?

+4
source share
1 answer

try it

 select plugged, max(counts) counts, month , year
 from 
    (select plugged ,count(*) as counts ,extract(month from tstamp) month , extract(year from tstamp) year from broadcast  where company=1 
      group by plugged,month ,year order by counts desc  ) as x ;
0

All Articles