SQL GROUP BY选择具有最高日期

时间:2016-08-28 17:20:25

标签: mysql sql

我有一个匹配参与者表,其中每个条目都有玩家,团队和日期字段。我想列出所有球员及其相应球队的名单,所以我做了类似

的事情
SELECT player, COUNT(DISTINCT matchid) matches, team FROM participants GROUP BY player

然而,如果一名球员改变了球队,它将为该球员返回一支随机(?)球队。有没有办法让它选择对应最高date字段的条目(所以它返回当前团队)?我尝试用participants替换(SELECT * FROM participants ORDER BY date DESC) x,但它似乎根本不会影响任何内容。

到目前为止,我所能想到的只是使用MID(MAX(CONCAT(date, '_', team)),12),但它假设date始终是一个10位数字,可能是也可能不是。

这是一个示例数据

MATCHID       PLAYER               TEAM               DATE
1             Bob                  Team A             1234567890
1             John                 Team A             1234567890
1             James                Team B             1234567890
1             Ross                 Team B             1234567890
2             James                Team A             1234567891
2             John                 Team A             1234567891
2             Bob                  Team B             1234567891
2             Ross                 Team B             1234567891

这表示A队(由Bob和John组成)和B队(由James和Ross组成)之间的比赛在1234567890进行。然后,Bob和James换队并在以后再打一场比赛。我想收到如下数据

PLAYER               TEAM               MATCHES
Bob                  Team B             2
John                 Team A             2
James                Team A             2
Ross                 Team B             2

但是,似乎没有办法保证Bob和James的参赛作品会显示正确的球队。

2 个答案:

答案 0 :(得分:0)

以下是一个解决方案:我刚刚将team列替换为核心子查询,该子查询选择由date DESC排序的第一个团队。

SELECT player, COUNT(DISTINCT matchid) matches, (
  SELECT team 
  FROM participants p2
  WHERE p2.player = p1.player
  ORDER BY `date` DESC
  LIMIT 1
) as team
FROM participants p1
GROUP BY player
ORDER BY team, player;;

另一个JOIN ON MAX(DATE)的解决方案:

SELECT plr.player, plr.matches, prt.team
FROM (
  SELECT player, COUNT(DISTINCT matchid) matches, MAX(`date`) as last_played
  FROM participants
  GROUP BY player
) plr
JOIN participants prt 
    ON  prt.player = plr.player
    AND prt.`date` = plr.last_played
ORDER BY prt.team, plr.player;

使用MAX(CONCAT()):

SELECT player, COUNT(DISTINCT matchid) matches,
  SUBSTR(MAX(CONCAT(LPAD(`DATE`, 10, 0), team)), 11) as team
FROM participants p1
GROUP BY player
ORDER BY team, player;

http://sqlfiddle.com/#!9/98f2f5/16

答案 1 :(得分:0)

您可以从group_concat中提取第一个小组:

SELECT   player,
         COUNT(DISTINCT matchid) matches,
         SUBSTRING_INDEX(GROUP_CONCAT(team ORDER BY date DESC SEPARATOR ','),',',1) team 
FROM     participants
GROUP BY player

请参阅SQL fiddle