我有两张桌子(MS Access)
tblInput
Event, UserID, Score EventA, 1, 50 EventA, 2, 55 EventB, 1, 45 EventB, 2, 33
tblUser
ID, Name 1 , John 2 , Alex
我需要显示每个事件,事件和人名的获胜分数。此示例的输出应为
Event, Name, Score EventA, Alex, 55 EventB, John, 45
我试过这个以获得活动和最高分:
SELECT Max(Score), Event FROM tblInput GROUP BY Event;
但是,如果我尝试选择ID
(我只是在名称的位置使用,可以在我加入表时更改回名称),我被迫将其作为聚合我不想要的功能,或者将它放在Group by语句中,我得到类似的内容
SELECT Max(Score) AS Score, Event, ID FROM tblInput GROUP BY Event, ID;
Score, Event, ID 165 EventA 2 173 EventA 9 170 EventA 32 211 EventB 10 224 EventB 14 256 EventC 16 188 EventC 17
感谢任何帮助,抱歉格式不佳。
答案 0 :(得分:2)
创建一个这样的查询:
SELECT
Max(Score) as topscore,
ChildEvent
FROM
T_Participation
GROUP BY ChildEvent
然后使用第一个查询构建第二个,并在事件和分数上加入输入表:
select
childEvent,
topscore,
StudentID
from
query1 q inner join
t_participation p on
q.childevent = p.childevent and
q.topscore = p.score
如果您有多个用户获得最高分,该怎么办? 与事件A一样,用户3的得分为55?
答案 1 :(得分:1)
这是一种可以在一个语句中完成的方法。您需要创建一个事件表及其最高分数。然后将该表连接回Input表。您的示例将您的表名称设为T_Input,但您的实现使用T_Participation。请将T_Participation替换为正确的表名称的T_Input。
SELECT T.EVENT, T.Score, U.Name
FROM T_Input T
INNER JOIN T_User U ON T.UserID = U.UserID
INNER JOIN
(
SELECT Event, MAX(Score) [Score]
FROM T_Input T2
INNER JOIN T_User U2 ON T2.UserID = U2.UserID
GROUP BY EVENT
)Top_scores ON T.EVENT = Top_scores.EVENT AND T.Score = Top_Scores.Score
答案 2 :(得分:1)
你可以这样做:
SELECT T_Input.Event, T_User.Name, T_Input.Score
FROM
(SELECT Max(Score), Event FROM T_Input GROUP BY Event) AS maxScores,
T_User,
T_Input
WHERE maxScores.score = T_Input.score
AND maxScores.Event = T_Input.event
AND T_User = T_Input.UserId