SQL只显示count函数的最高值

时间:2013-03-17 20:03:01

标签: mysql sql count distinct-values

Select Distinct id as personID, count(tid) as Sales
From salesTable
Group by personID;

目前的结果是:(我需要顶级销售才能显示。)

 personID  | Sales
_____________________
   1000      | 2
   1020      | 1
   1040      | 2
   1060      | 1
   1080      | 2
   1140      | 1
   1160      | 1
   _________________

salesTable看起来像这样:

id  | tid
_________
1000|201
1020|202
1040|203
1000|204
1060|205
1080|206
1040|207
1080|208
1140|209
1160|210

我想要的结果应如下所示:

personID  | Sales
_____________________
   1000      | 2
   1040      | 2
   1080      | 2
  _________________

2 个答案:

答案 0 :(得分:3)

select  id as personID
,       count(tid) as Sales
From    salesTable
group by 
        id
having  count(tid) =
        (
        select  max(Sales)
        from    (
                select  count(tid) as Sales
                from    salesTable
                group by
                        id
                ) SubQueryAlias
        )

答案 1 :(得分:1)

稍微简单有序:

SELECT id as personID
      ,count(tid) AS Sales
FROM   salesTable
GROUP  BY id
HAVING count(tid) =
   (
   SELECT count(tid)
   FROM   salesTable
   GROUP  BY id
   ORDER  BY count(tid) DESC
   LIMIT  1
   )
ORDER  BY personID;

->SQLfiddle demo.