按顺序平均

时间:2011-08-11 10:49:10

标签: sql-server tsql sql-order-by

我有这个问题:

SELECT 
   Field1
   AVG(Field2) as Field2, 
   AVG(Field3) as Field3, 
   AVG(Field4) as Field4 
FROM Table1
GROUP BY Field1
ORDER BY Field2 DESC, Field3 DESC, Field4 DESC

如何(如果可能)订购三个字段的平均值? 我想在获得平均三个字段后进行单个订单。例如:

...
ORDER BY (Field2 + Field3 + Field4) / 3

3 个答案:

答案 0 :(得分:3)

要对Field1 + Field2 + Field3的平均值进行排序,您可以添加新字段并对其进行排序。

select Field1,   
       avg(Field2) as AField2, 
       avg(Field3) as AField3, 
       avg(Field4) as AField4,
       avg(Field2+Field3+Field4) as Sort
from Table1
group by Field1
order by Sort desc

或者您可以将查询放在子查询中,并对外部查询中字段的总和进行排序。

select T.Field1,
       T.AField2,
       T.AField3,
       T.AField4
from (select Field1,   
             avg(Field2) as AField2, 
             avg(Field3) as AField3, 
             avg(Field4) as AField4
      from Table1
      group by Field1) as T
order by T.AField2 + T.AField3 + T.AField4 desc

答案 1 :(得分:1)

SELECT 
   AVG(Field1) as AvgField1, 
   AVG(Field2) as AvgField2, 
   AVG(Field3) as AvgField3 
FROM Table1
   ORDER BY AvgField1 DESC, AvgField2 DESC, AvgField3 DESC

OR:

SELECT 
   AVG(Field1) as Field1, 
   AVG(Field2) as Field2, 
   AVG(Field3) as Field3 
FROM Table1
   ORDER BY AVG(Field1) DESC, AVG(Field2) DESC, AVG(Field3) DESC

答案 2 :(得分:1)

;WITH Input(Field1, Field2, Field3)
AS
(
SELECT     
      AVG(Field1) as Field1,     
      AVG(Field2) as Field2,     
      AVG(Field3) as Field3  
    FROM Table1    
)
SELECT Field1, Field2, Field3 
FROM Input    
ORDER BY Field1 DESC, Field2 DESC, Field3 DESC