无法理解结果

时间:2019-01-03 05:04:09

标签: sql sql-server

我无法理解两种不同的结果。 我正在尝试按学生的平均成绩来获得学生GPA的前10%。

enter image description here

select top 10 percent avg (markrate) as GPA
from mark

输出:

enter image description here

现在查询时

select top 10 percent avg (markrate) as gpa, studentid
from mark
group by studentid

enter image description here

我认为这是因为有大量的StudentID 1和2,所以平均GPA发生了变化

现在

  select top 10 percent avg (markrate) as gpa, studentid
  from mark
  group by studentid
  order by gpa

为什么最终得到82和2?为什么这是正确的答案?

enter image description here

3 个答案:

答案 0 :(得分:2)

此查询:

select top 10 percent avg(markrate) as gpa, studentid
from mark
group by studentid

可能未达到您的期望。它通过studentid汇总 all 个数据。然后,它占结果行的“前10%”。 SQL Server将此取整为1行。

哪一行? 任意行。不建议在不使用top的情况下使用order by,因为您会得到不确定的行。如果您在没有top(或top 100 percent)的情况下运行查询,则会看到每个学生的平均值。这些行之一是任意选择的。

添加order by gpa时,您得到的GPA最低。平均值是82,而不是82.5,因为该列是整数-所以结果是整数。

我将更倾向于使用十进制数字查看结果-并考虑联系:

select top 10 percent with ties avg(markrate * 1.0) as gpa, studentid
from mark
group by studentid
order by gpa

答案 1 :(得分:0)

因为StudentID 2是gpa较低的那个,根据我的计算,它是82.5 GPA,但我想MarkRate的数据类型是整数,因此将其舍入到82

答案 2 :(得分:0)

在没有top 10 percent的情况下尝试查询,希望它可以消除您的疑问。

1。。与您在第一个查询中一样,没有使用top 10 percent

select avg (markrate) as GPA
from mark

这将仅返回一条记录,该记录将是avg的{​​{1}}值。如果您使用markrate,它将从完整结果中返回10%的行。

2。。在第二个查询中,不使用top 10 percent

top 10 percent

3。。这将返回四个记录,即每个select avg (markrate) as gpa, studentid from mark group by studentid 的{​​{1}}的{​​{1}}值。如果您使用avg,它将从这4行结果中返回10%行。

在您的第三个查询中,与第二个查询相同,但结果按markrate排序,因此它显示的结果与第二个查询不同。