SQL最大值表单计数()

时间:2017-06-16 19:15:00

标签: mysql sql count

我有以下问题:

SELECT BusID, count(BusID) as 'NoofConnections'
FROM mytable
Group By BusID
Order by BusID

我得到了下表:

BusID   NoofConnections
=========================
1       6
2       6
4       3
5       2
3       1

我将从NoofConnections中选择最大值,因此在这种情况下,LIMIT 1不起作用,因此我们有两个相等的值。像这样:

 BusID   NoofConnections
=========================
1            6
2            6

任何想法?

2 个答案:

答案 0 :(得分:2)

您可以使用子查询:

SELECT BusID, COUNT(*) as NoofConnections
FROM mytable
GROUP BY BusID
HAVING COUNT(*) = (SELECT COUNT(*)
                   FROM mytable
                   GROUP BY BusID
                   ORDER BY COUNT(*) DESC
                   LIMIT 1
                  )
ORDER BY BusID;

答案 1 :(得分:0)

您可以使用子选择

  select * from (
    SELECT BusID, count(BusID) as NoofConnections
    FROM mytable
    Group By BusID

  )  t1 
  where t1.NoofConnections = (  select max(NoofConnections)
      from (
      SELECT BusID, count(BusID) as NoofConnections
      FROM mytable
      Group By BusID
      )