0

有两行的最高值为 5,但下面的查询只返回最后一个最高记录......我怎样才能获得成员值最高的所有行?

我可以使用 max is where 子句请帮忙吗?

SELECT teamcode,MAX(member) AS members FROM(
    SELECT t.`teamcode` AS teamcode,
    COUNT(*) AS member
    FROM `users` u
    JOIN teams t
    ON u.teamcode=t.tm_id
    GROUP BY `teamcode`
) AS maxcount

如何获得所有最高值?

4

3 回答 3

1

您可能会更好地从 WHERE 子句中获取具有最大值的行,例如:
WHERE member = MAX(member)
而不是尝试在 SELECT 子句中执行此操作。

编辑:我在这里扩展了我对 SQL 的了解,但试试这个:
SELECT teamcode, member
FROM(
SELECT t.'teamcode' AS teamcode, COUNT(*) AS member
FROM 'users' u JOIN teams t ON u.teamcode = t.tm_id
GROUP BY 'teamcode'
HAVING member = MAX(member)
) AS maxcount

于 2013-08-13T14:44:45.410 回答
1

首先,因为您只想使用团队代码进行计数:您不需要使用JOIN! 但是,您确实需要一个辅助表。

  SELECT teamcode,
         COUNT(*) as members
    FROM users
GROUP BY teamcode
  HAVING COUNT(*) = (   SELECT COUNT(*)
                          FROM users
                      GROUP BY teamcode
                      ORDER BY COUNT(*) DESC
                         LIMIT 1             );

SQL-Fiddle,如果你愿意的话。

使用过的参考资料: SQL Query of Using Functions - How to get MAXIMUM Count of the list

于 2013-08-13T16:08:06.850 回答
0

如果您不仅想要查询中的最大值,最好使用 GROUP BY。

SELECT teamcode,MAX(member) AS members FROM(
    SELECT t.`teamcode` AS teamcode,
    COUNT(*) AS member
    FROM `users` u
    JOIN teams t
    ON u.teamcode=t.tm_id
    GROUP BY `teamcode`
) AS maxcount
GROUP BY teamcode

如果你想要五个最高值中的两个,你应该使用子句“LIMIT”。

于 2013-08-13T17:26:45.000 回答