组内的mysql最大计数

时间:2014-02-20 18:13:50

标签: mysql

我有一张表如下

id  qNum  opNum
1   1     3
2   1     3
3   1     2
4   1     1
5   2     4
6   2     4
7   2     4
8   2     1

我需要按qNum和opNum分组计数,这很好,但我只想返回每个分组中最大计数的记录的qNum和opNum

所以我理想情况下需要一个看起来像

的记录集
qNum  opNum  maxCount
1     3      2
2     4      3

非常感谢帮助!

2 个答案:

答案 0 :(得分:1)

虽然看起来并不漂亮,但我认为它可以达到您想要的效果:

select y.qnum, y.opnum, maxcnt
from (
    select qnum, opnum, count(*) cnt
    from yourtable
    group by qnum, opnum
  ) y
  join (
    select qnum, max(cnt) maxcnt
    from (
      select qnum, opnum, count(*) cnt
      from yourtable
      group by qnum, opnum) t
    group by qnum
    ) t on y.qnum = t.qnum and y.cnt = t.maxcnt

答案 1 :(得分:1)

更简单的解决方案可能是:

SELECT qNum, opNum, MAX(temp.maxcount) AS maxcount FROM(
SELECT qNum, opNum, COUNT(*) AS maxCount
FROM t
GROUP BY opNum, qNum ORDER BY maxcount DESC
) AS temp GROUP BY qNum