我正在使用SQL Server数据库。
鉴于以下查询,我试图获得每个班级的最高分。 Scores
表有两行50行,所以我想要总共2行。但是,因为我有Scores.Id
,所以它返回Scores
的每一行,因为Scores.Id
是唯一的。当然,简单的解决方案是删除Scores.Id
列,除了我需要知道Scores.Id
以进行其他查找。
SELECT
Class_Id, Scores.Id, MAX(Scores.ClassScore) AS Score
FROM
Classes
INNER JOIN
Scores ON Classes.Id = Scores.Class_Id
GROUP BY
Scores.Class_Id, Scores.Id
答案 0 :(得分:4)
这是你想要的吗?
[$parse:syntax] Syntax Error: Token '{' is unexpected, expecting [)] at column 45 of the expression [vm.solderEcriture('debit',ecriture,formName_{{$index}}.$valid)] starting at [{{$index}}.$valid)].
根据您想要的信息,加入select s.*
from (select s.*,
max(s.classscore) over (partition by s.class_id) as max_classscore
from scores s
) s
where classscore = max_classscore;
是多余的。
答案 1 :(得分:3)
class_id的最高分数只是
select class_id, max(classScore) score from scores
group by class_id
如果您需要知道得分表中哪些行具有最高得分,您可以进行加入。如果每个班级的最高分数超过一个,则可能会有两行以上。
select id, class_id, classscore from
scores s
inner join
(
select class_id, max(classScore) score from scores
group by class_id
)
t
on t.class_id = s.class_id and t.score = s.classScore
或者我可能会使用cte
with maxScores as
(
select class_id, max(classScore) score from scores
group by class_id
)
select id, class_id, classscore from
scores s
on maxScores.class_id = s.class_id and maxScores.score = s.classScore
答案 2 :(得分:2)
这看起来像是rank
窗口函数的作业:
SELECT Class_Id, Id, Score
FROM (SELECT Class_Id, Scores.Id AS Id, Score,
RANK() OVER (PARTITION BY Class_Id, Scores.Id
ORDER BY Score DESC) AS rk
FROM Classes
JOIN Scores ON Classes.Id = Scores.Class_Id) t
WHERE rk = 1