在创建SQL语句时需要帮助

时间:2019-02-05 09:02:35

标签: mysql sql

这是表格数据

Name       Stage ID       Event ID     Attempt No            Score
Ramesh        1             1             1                    10
Ramesh        1             1             2                    20
Ramesh        2             1             1                    30
Suresh        1             1             1                    05
Suresh        2             1             1                    15
Suresh        2             2             1                    25
Suresh        2             2             2                    35
Suresh        2             2             3                    30

我们有一个表,其中包含名称,阶段ID,事件ID,尝试编号,得分。

我们要对数据进行分组,包括名称,阶段ID,事件ID,尝试次数,最大(得分)

在阶段,事件和名称下,每次尝试都有记录,我们需要获取最高分,并且需要显示相同的记录。

输出应为:

Name       Stage ID       Event ID     Attempt No            Score
Ramesh        1             1             2                    20
Ramesh        2             1             1                    30
Suresh        1             1             1                    05
Suresh        2             1             1                    15
Suresh        2             2             2                    35

对于姓名+舞台+事件的组合,这将有一条记录

2 个答案:

答案 0 :(得分:1)

您可以在下面使用相关子查询尝试

select * from tablename t1
where score in 
    (select max(score) from tablename t2 where t1.name=t2.name and t1.stage=t2.stage 
      and t1.eventid=t2.eventid)

答案 1 :(得分:0)

您可以在子查询上使用内部联接以获得所需的最大值

select yt.* 
from your_table yt
INNER JOIN ( 
    select Name, Stage_ID, Event_ID, Attempt_No, max(score) max_score 
    from your_table 
    group by  Name,  Stage_ID, Event_ID, Attempt_No
) t on yt.name  = t.name 
      and yt.Stage_ID = t.Stage_ID
          and yt.Event_ID = t.Event_ID 
            and yt.Attempt_No = t.Attempt_No 
              and yt.score  = t.max_score   join