从每位成员的最佳2分获得总分

时间:2018-06-26 21:39:56

标签: mysql sql

我有一个问题,下面的代码计算出所有输入的成员的总得分,而不是将其限制为最好的2分。它似乎不喜欢重复的得分,并且在某些成员得分小于2的情况下不会将它们相加得分显示他们的得分超过2分。

create table members(id int, name char, handicap int);

insert into members(id, name, handicap)
values(1, 'Bob', 12);

insert into members(id, name, handicap)
values(2, 'John', 14);

create table results(member_id int, course_id int, score int, position int);

insert into results(member_id int, course_id int, score int, position int)
values(1,1,36,1);

insert into results(member_id int, course_id int, score int, position int)
values(1,2,34,2);

insert into results(member_id int, course_id int, score int, position int)
values(2,1,27,2);

insert into results(member_id int, course_id int, score int, position int)
values(2,2,35,2);

insert into results(member_id int, course_id int, score int, position int)
values(2,3,35,2);

insert into results(member_id int, course_id int, score int, position int)
values(1,3,38,1);

并获取数据

SELECT name, handicap, best, total FROM
(SELECT name, id, curr_handicap as handicap,  GROUP_CONCAT(score order by score DESC SEPARATOR ' | ') as best,
sum(score) as total
 FROM members m join (SELECT member_id, score, course_id
  FROM results m
  WHERE(
    SELECT COUNT(*)
    FROM results mT
    WHERE mT.member_id = m.member_id and mT.score >= m.score) <= 2 )  r
    on m.id = r.member_id 
    group by member_id
    ORDER BY total, member_id DESC, name, MIN(course_id) ASC
) AS T1
group by name
order by total DESC

我希望所需的结果看起来像这样:

    <table>
    <tr><td>Name</td><td>Handicap</td><td>Total score</td><td>Best 2 scores</td> 
   </tr>
    <tr><td>Bob</td><td>12</td><td>74</td><td>38 | 36</td></tr>
    <tr><td>John</td><td>14</td><td>70</td><td>35 | 35</td></tr>
    </table>

但是,我只能从所有球员的得分中得到总分,并且最好的2分并不总是相同的。

1 个答案:

答案 0 :(得分:0)

如果有人对此感兴趣或卡住了。 我需要在此表中为每个成员显示最好的6分。我希望获得最好的6分的总分,而不仅仅是该成员的总分。

下面使用变量的解决方案比我想象的要简单得多!

SELECT name, handicap, best, total FROM
 (SELECT name, id, curr_handicap as handicap,  GROUP_CONCAT(score order by score DESC 
 SEPARATOR ' | ') as best,
 sum(score) as total
 FROM members m join (select member_id, score, course_id, result_id
 from
   (
     SELECT member_id, score, course_id, result_id,
     (@row:=if(@prev=member_id, @row +1, if(@prev:= member_id, 1, 1))) rn
     FROM results t
     CROSS JOIN (select @row:=0, @prev:=null) c
     order by member_id, score desc 
   ) src
 where rn <= 6
 order by member_id, score)  r
 on m.id = r.member_id 
 group by member_id
 ORDER BY total, member_id DESC
 ) AS T1
group by name
order by total DESC");