SQL想问一下Select子句

时间:2016-12-24 01:14:20

标签: sql-server select subquery

我有这个SQL语句:

select max(avrg) 
from (select sum(points) as avrg 
      from marks 
      group by num_eleve) s;

我在使其工作时遇到了问题,结果发现我在最后需要s,没有声明就失败了。

我想了解s的作用,换句话说,为什么上述工作会在以下失败时发挥作用?

select max(avrg) 
from (select sum(points) as avrg 
      from marks 
      group by num_eleve);

2 个答案:

答案 0 :(得分:0)

select max(avrg) 
from (select sum(points) as avrg 
      from marks 
      group by num_eleve) s;

在上面的查询中,ssub-select

的别名
(select sum(points) as avrg from marks group by num_eleve)

它将用于引用Sub-select中的列。您的查询可以写成

select max(s.avrg)  --here I have added s.avrg 
from (select sum(points) as avrg 
      from marks 
      group by num_eleve) s;

另外,如果您想将子选择与另一个名为avrg的列的表连接,那么要区分您想要的avrg列值s

select max(s.avrg)  --here I have added s.avrg to pull valued from sub-select not from another_table 
from (select sum(points) as avrg 
      from marks  
      group by num_eleve) s Left join another_table b on s.avrg = b.avrg 

答案 1 :(得分:0)

这条查询:

(select sum(points) as avrg from marks group by num_eleve)

充当表格,只需要一个名称。 " s"会做,但它可以是任何东西。如果你愿意,你可以称之为MyTable或Averages或Mxyzptlk。