我有下表:
我需要选择某个日期所有玩家的最高分数。
例如,我需要球员2000-1-1之后取得的最高成绩: 预期结果:
我尝试了以下选择:
select *
from player_score ps
where ps.created_at >= '2000-1-1'
and ps.score = (select max(ps2.score)
from player_score ps2
where ps2.player_id = ps.player_id)
但它只返回一条记录:
您能否告诉我,达到预期效果的最佳方法是什么?谢谢。
答案 0 :(得分:1)
由于您希望每位玩家max
,请执行group by player_id
select ps.player_id, max(ps.score)
from player_score ps
where ps.created_at >= '2000-1-1' group by ps.player_id
答案 1 :(得分:1)
您还需要在子查询中按日期进行过滤:
;with cte (player_id,MaxScore) as (
select ps.player_id, max(ps.score) as MaxScore
from player_score ps
where ps.created_at >= '2000-1-1'
group by ps.player_id
)
select ps.*
from player_score ps
inner join cte on cte.player_id = ps.player_id and cte.MaxScore = ps.Score
where ps.created_at >= '2000-1-1'
其他玩家的截止日期之前出现了总的最大值,这就是为什么没有行的原因。
如果您任意地希望每位玩家获得一个记录,即使有最高分的平局,那么请比较ID而不是得分:
select ps.*
from player_score ps
where ps.created_at >= '2000-01-01'
and ps.score = (select max(ps2.score)
from player_score ps2
where ps2.created_at >= '2000-01-01' and
ps2.player_id = ps.player_id
);
在Postgres中,最简单的解决方案是:
select ps.*
from player_score ps
where ps.created_at >= '2000-01-01'
and ps.id = (select ps2.id
from player_score ps2
where ps2.created_at >= '2000-01-01' and
ps2.player_id = ps.player_id
order by ps2.score desc
limit 1
);
答案 2 :(得分:1)
除了Gordon Linoff的解决方案之外,您还可以使用IN
谓词来解决它。
但是请确保将GROUP BY
子句放在子查询中,而不是外部查询中。
SELECT id,
player_id,
score,
created_at
FROM player_score ps2
WHERE ps2.score IN (SELECT MAX(score) FROM player_score ps
WHERE created_at >= '2000-1-1' AND ps.player_id = ps2.player_id
GROUP BY ps.player_id)
ORDER BY player_id
答案 3 :(得分:0)
最大值始终是一个值,因此,如果您需要更多值,请联系我们“按订单排序” 它将返回从上到下降序的所有值,并且您可以在表格顶部看到最大值
答案 4 :(得分:0)
关于@krithikaGopalakrisnan的答案,假设您需要结果集中的ID和CreatedDate列,则可以使用:
public class CustomValidator : AbstractValidator<Customer> {
public CustomValidator()
{
RuleFor(obj => obj.Prop).NotNull().WithSeverity(Severity.Error);
RuleFor(obj => obj.Prop).NotEqual("foo").WithSeverity(Severity.Warning);
}
}