如何在SQL Server 2008中从Avg中查找Max

时间:2018-08-26 08:29:48

标签: sql sql-server sql-server-2008

select
    max(total_price_new) 
from
    (select
         avg(Total_Price) as total_price_new, 
         Document_Ref  
     from
         TBL_Sales
     group by
         Document_Ref)

这在SQLite中有效,但在SQL Server 2008中不适用。

我收到此错误:

enter image description here

有人可以知道替代解决方案吗?

4 个答案:

答案 0 :(得分:4)

您需要表名别名,例如Tname

select max(total_price_new) 
from  ( 
  select avg(Total_Price) as total_price_new, Document_Ref 
  from  TBL_Sales
group by Document_Ref
)  Tname 

答案 1 :(得分:3)

内部查询需要 q):

select max(q.total_price_new) 
  from  ( select avg(Total_Price) as total_price_new, Document_Ref 
            from TBL_Sales
           group by Document_Ref) as q;

This参考可能会有所帮助。

答案 2 :(得分:2)

在编写任何内部子查询时,您必须输入该子查询名称,以便从该子查询结果中选择数据到外部查询中,因此您只需要子查询的别名

select
    max(total_price_new) 
from
    (select
         avg(Total_Price) as total_price_new, 
         Document_Ref  
     from
         TBL_Sales
     group by
         Document_Ref) as T

答案 3 :(得分:1)

您不需要子查询:

select top (1) avg(Total_Price) as total_price_new
from TBL_Sales
group by Document_Ref
order by total_price_new desc;

此方法的一个优点是,您还可以拉回平均值最高的Document_Ref