SQL根据条件从列中获取最常见的值

时间:2016-11-07 08:29:49

标签: mysql sql

此查询

# PlayerID, HeroTypeID, HeroTypeIDCount, WinRate, Wins, Losses
'1', '11', '1', '1.0000', '1', '0'
'1', '13', '3', '0.3333', '1', '2'
'1', '24', '5', '0.8000', '4', '1'
'1', '27', '1', '1.0000', '1', '0'
'2', '28', '1', '0.0000', '0', '1'
'2', '6', '1', '0.0000', '0', '1'
'2', '30', '1', '0.0000', '0', '1'
'2', '7', '1', '1.0000', '1', '0'

产生以下结果:

PlayerID, HeroTypeID, HeroTypeIDCount, WinRate, Wins, Losses
       1,         24,               5,  0.8000,    4,      1
       2,          7,               1,  1.0000,    1,      0

我想要做的是每个PlayerID获得最常见的FK_HeroTypeID(也是HeroTypeIDCount的最高值),但是如果是tie,则最高的winrate应该优先。以下是我想要获得的一个例子:

s = set(arr)
print(len(A.intersection(s)) - len(B.intersection(s)))

你应该怎么写这样的查询?

编辑:

好的,这里是生成结果的简单创建/插入表。

http://sqlfiddle.com/#!9/d644a

1 个答案:

答案 0 :(得分:1)

SELECT playerid
     , herotypeid
     , herotypeidcount
     , winrate
     , wins
     , losses 
  FROM 
     ( SELECT *
            , CASE WHEN @prev=playerid THEN @i:=@i+1 ELSE @i:=1 END rank
            , @prev:=playerid prev 
         FROM table1
            , (SELECT @prev:=null,@i:=0) vars 
        ORDER 
           BY herotypeidcount DESC
            , winrate DESC
     ) x 
 WHERE rank = 1;

这是一个'黑客'解决方案。它有效,但真的不应该依赖......

 SELECT * 
   FROM 
      ( SELECT * 
          FROM table1 
         ORDER 
            BY herotypeidcount DESC
             , winrate DESC
      ) x
  GROUP 
     BY playerid