4

嗨,我有下表,我想选择每个月插入的 max(count(*))。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

因此,如果我执行以下操作:

    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;

输出:

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

所需的输出:

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

这是正确的......但我只想要 max(count(*)) (例如在这种情况下只有第一行)。在某些情况下,有 2 行具有最大计数,但对于每个月/年,我只想返回最大计数行...我需要内部选择语句还是什么?

4

1 回答 1

0

尝试这个

 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 ;
于 2013-09-30T23:13:41.497 回答