SQL Server:如何获取Top(n)和Bottom(n)记录的平均值

时间:2017-12-07 18:17:05

标签: sql

我有一张分数表:

Student ¦ Score
  A     ¦ 23.5
  B     ¦ 34.9

如何获得ALL的平均值,前15%和后15%这样:

Average ¦ top15Avg ¦ bottom15Avg

感谢。

1 个答案:

答案 0 :(得分:0)

首先计算15%的行数。 然后你可以做这样的选择和平均值:

declare @pct int, @all float, @top float, @bottom float
select  @pct = 0.15 * COUNT(*) from Students

select @all = AVG(score) from Students
select @top = AVG(score) from (select top (@pct) score from Students order by score desc)
select @bottom = AVG(score) as 'bottom15Avg' from (select top (@pct) score from Students order by score asc)
select @all as 'Average', @top as 'top15Avg', @bottom  as 'bottom15Avg'