您可以通过几种方式执行此操作,包括 @Ben 显示的内容。从主要是 SQL Server 的背景来看,我很好奇是否可以只使用 ROWNUM,并发现关于ROWNUM 与 ROW_NUMBER的这篇文章很有趣。我不确定它是否过时。
全部在SQLFiddle中。
注意:我使用的是子查询分解/CTE,因为我认为读取比内联子查询更清楚。
使用 ROWNUM:
WITH OrderedScore AS (
SELECT id, game_no, score
,rownum as score_rank
FROM GameScore
WHERE game_no = 1
ORDER BY Score ASC
)
SELECT id
,sum(score)/count(score)
FROM OrderedScore
WHERE score_rank > 1
GROUP BY id;
像 Ben 一样使用 ROW_NUMBER() OVER(ORDER BY...) :
WITH OrderedScore AS (
SELECT id, game_no, score
,ROW_NUMBER() OVER(ORDER BY score ASC) as score_rank
FROM GameScore
WHERE game_no = 1
ORDER BY Score ASC
)
SELECT id
,sum(score)/count(score)
FROM OrderedScore
WHERE score_rank > 1
GROUP BY id;
使用 ROW_NUMBER() OVER(PARTION BY...ORDER BY...) 如果您想在某个时候通过 game_no 或 id 删除低分,我认为这会带来更大的灵活性:
WITH OrderedScore AS (
SELECT id, game_no, score
,ROW_NUMBER() OVER(PARTITION BY id ORDER BY score ASC) as score_rank
FROM GameScore
WHERE game_no = 1
ORDER BY Score ASC
)
SELECT id
,sum(score)/count(score)
FROM OrderedScore
WHERE score_rank > 1
GROUP BY id;