选择具有另一个ID

时间:2015-06-16 03:12:04

标签: mysql sql count

我有一个带有PlayerID和TypeID的棒球比赛数据库(比赛类型:双击,击出等)。数据看起来像这样:

+----------+--------+
| playerid | typeid |
+----------+--------+
|        2 |      4 |
|        2 |      4 |
|        2 |      7 |
|        3 |      7 |
|        3 |      7 |
|        3 |      7 |
|        3 |     26 |
|        3 |      7 |

我正在努力寻找哪种球员最能发挥各种类型。例如。 Jim(PlayerID 3)获得最多击球(TypeID 7)和Bob(PlayerID 2)拥有最多本垒打(TypeID 4),这应该产生下表:

+----------+--------+----------------+
| playerid | typeid | max(playcount) |
+----------+--------+----------------+
|        2 |      4 |             12 |
|        3 |      7 |              9 |
|        3 |     26 |              1 |

到目前为止,我最好的尝试是:

SELECT playerid,typeid,MAX(playcount) FROM 
(
SELECT playerid,typeid,COUNT(*) playcount FROM plays GROUP BY playerid,typeid
) AS t GROUP BY typeid;

返回每种类型的正确最大值,但关联的PlayerID都是错误的,我无法弄清楚原因。我敢肯定我错过了一些简单的东西(或者让它过于复杂),但无法弄明白。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

在MySQL中,这个群体=明智的最大值,遗憾的是,它并不像你想要的那样简单。

以下是使用类似于ROW_NUMBER() in MySQL

中建议的方法来实现此目的的方法
SELECT a.*
  FROM (
        SELECT playerid
              ,typeid
              ,COUNT(*) playcount 
          FROM plays 
         GROUP BY playerid,typeid
        ) a
  LEFT JOIN
        (
        SELECT playerid
              ,typeid
              ,COUNT(*) playcount 
          FROM plays 
         GROUP BY playerid,typeid
        ) b
    ON a.typeid = b.typeid
   AND a.playcount < b.playcount
WHERE b.playerid IS NULL

答案 1 :(得分:1)

这会有用吗?

SELECT
    playertypecounts.*
FROM
    (SELECT
       playerid,
       typeid,
       COUNT(*) as playcount
     FROM plays
     GROUP BY playerid, typeid) playertypecounts
INNER JOIN
    (SELECT
        typeid,
        MAX(playcount) as maxplaycount
     FROM 
        (SELECT
           playerid,
           typeid,
           COUNT(*) as playcount
         FROM plays
         GROUP BY playerid, typeid) playcounts
     GROUP BY typeid) maxplaycounts
ON playertypecounts.typeid = maxplaycounts.typeid
AND playertypecounts.playcount = maxplaycounts.maxplaycount

查询块的这一部分返回每个typeid的最大游戏次数:

(SELECT
    typeid,
    MAX(playcount) as maxplaycount
 FROM 
    (SELECT
       playerid,
       typeid,
       COUNT(*) as playcount
     FROM plays
     GROUP BY playerid, typeid) playcounts
 GROUP BY typeid) maxplaycounts

然后它内部连接到所有typeid / playcounts,以便过滤那些玩家对任何给定typeid具有最大计数的计数。

请参阅SQLFiddle example

说了这么多,我实际上更喜欢@KarlKieninger的回答,因为它更优雅。

答案 2 :(得分:1)

你必须将playerid列也放在group by子句中。 休息一切都好。

SELECT playerid,typeid,MAX(playcount) FROM 
(
SELECT playerid,typeid,COUNT(*) playcount FROM plays GROUP BY playerid,typeid
) AS t GROUP BY playerid,typeid;