MySQL选择列值的最大计数

时间:2016-03-26 01:57:15

标签: mysql sql

我有一张名为Euro_Cup的表。

[在此处输入图像说明] [1]

Group   Country Rank    Jersey  Position    Age Selections  Club    Player
A   Brazil  3   18  Midfielder  29  24  Internazionale      Hernanes
A   Cameroon    56  18  Midfielder  28  38  Antalyaspor     Eyong Enoh
A   Croatia 18  18  Forward 34  92  VfL Wolfsburg   Ivica Olic
A   Mexico  20  18  Defender    27  104 Bayer Leverkusen    Andres Guardado
B   Australia   62  18  Goalie  32  8   Adelaide United     Eugene Galekovic
B   Chile   14  18  Defender    28  65  Nottingham Forest   Gonzalo Jara
B   Spain   1   18  Defender    25  26  Barcelona       Jordi Alba
B   Netherlands 15  18  Midfielder  24  6   Norwich City    Leroy Fer

我必须编写一个SQL查询,根据球衣号码对球员进行分组,然后为每个球衣号码组返回该球衣号码的最常见位置。

E.g球衣号码18有3个Midfilders,8个后卫和2个守门员然后结果应该是球衣号码18,后卫(bcos max球员,球衣号码18)

我试过了

 select jersey,position,count(position) as cnt 
 from euro_cup2
 group by jersey,position 
 having count(position) in 
                       (select max(cnt) from   (select jersey,position,count(position) as cnt 
                      from euro_cup2
                       group by jersey,position)a)

但它不起作用。任何帮助都将受到高度赞赏

2 个答案:

答案 0 :(得分:0)

我查看了您的所有评论,这将为您提供搜索内容:

SELECT
euro_cup2.jersey,
a.position,
MAX(cnt) as count
FROM euro_cup2
LEFT JOIN
(SELECT
   jersey,
   position,
   (COUNT(position)) AS cnt 
   FROM euro_cup2
   GROUP BY jersey,position) AS a ON euro_cup2.jersey=a.jersey
GROUP BY jersey;

结果如下:

Here the result

此致

答案 1 :(得分:0)

尝试这个,应该工作

   SELECT Jersey,
   Group_concat(Position separator ','),
   Group_concat(CountOfPosition separator ',')
   FROM   (SELECT euro_cup.Jersey,
           euro_cup.Position,
           Count(euro_cup.Position) AS CountOfPosition
    FROM   euro_cup
    GROUP  BY euro_cup.jersey,
              euro_cup.Position) a
   WHERE  CountOfPosition = (SELECT Max(CountOfPosition)
                     FROM   (SELECT euro_cup.jersey,
                                    euro_cup.Position,
                                    Count(euro_cup.Position) AS      CountOfPosition
                             FROM   euro_cup
                             GROUP  BY euro_cup.jersey,
                                       euro_cup.Position) b
                     WHERE  a.jersey = b.jersey)
     GROUP  BY Jersey