这是我的table
http://www.sqlfiddle.com/#!2/47e2d/8
╔════╦══════════╦════════╦═══════╦════════╗
║ id ║ category ║ userid ║ users ║ points ║
╠════╬══════════╬════════╬═══════╬════════╣
║ 1 ║ 2 ║ 91 ║ user1 ║ 100 ║
║ 2 ║ 3 ║ 92 ║ user2 ║ 80 ║
║ 3 ║ 4 ║ 93 ║ user3 ║ 10 ║
║ 4 ║ 4 ║ 91 ║ user1 ║ 12 ║
╚════╩══════════╩════════╩═══════╩════════╝
如何获得每个类别中得分最高的用户的计数结果?
在上面的例子中,我想得到
user1: 2
user2: 1
在stackoverflow中搜索类似的问题一段时间之后,我想出了
SELECT users, COUNT(*)
FROM `table`
WHERE points=(SELECT MAX(points) FROM `table`)
GROUP BY points;
但它不会产生我想要的东西。
答案 0 :(得分:2)
试试这个:
SELECT
users,
COUNT(*)
FROM
(SELECT
users,
COUNT(*) COUNT
FROM
`table`
WHERE points IN
(SELECT
MAX(points)
FROM
`table`
GROUP BY category)
GROUP BY points) temp
GROUP BY users ;
答案 1 :(得分:2)
试试这个:
SELECT
t1.users,
COUNT(t2.category)
FROM `table` AS t1
INNER JOIN
(
SELECT category, MAX(points) MAxpoints
FROM `table`
GROUP BY category
) AS t2 ON t1.category = t2.category AND t1.points = t2.MAxpoints
GROUP BY t1.users;
加入的子查询:
SELECT category, MAX(points) MAxpoints
FROM `table`
GROUP BY category
会为每个类别提供最大points
,然后我们通过将该子查询与原始表一起加入那些最大点的用户,然后我们使用COUNT
来计算这些类别的每个用户的最高分数。
这会给你:
╔════════╦═══════╗
║ USERS ║ COUNT ║
╠════════╬═══════╣
║ user1 ║ 2 ║
║ user2 ║ 1 ║
╚════════╩═══════╝
答案 2 :(得分:2)
试试这个:
SELECT users, count(*)
FROM `TABLE`,
(SELECT category, max(points) as max_points FROM `TABLE` GROUP BY category) as maxes
WHERE maxes.category = `TABLE`.category AND maxes.max_points = `TABLE`.points
GROUP BY users
这里的关键是创建一个临时表,其中包含每个类别的最大点
SELECT category, max(points) as max_points FROM `TABLE` GROUP BY category
然后我使用它来加入现有的TABLE
以找到具有最大分数的正确用户。