Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average in order by clause

I have this query:

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

How to (if is possible) order with average of the three fields? I want to make a single order after getting an average of three fields. For example:

...
ORDER BY (Field2 + Field3 + Field4) / 3
like image 448
Alberto Rubini Avatar asked Aug 11 '11 10:08

Alberto Rubini


People also ask

What is ORDER BY clause with example?

The SQL ORDER BY clause is used to sort the result set in either ascending or descending order. For example, SELECT * FROM Customers ORDER BY first_name; Run Code. Here, the SQL command selects all customers and then sorts them in ascending order by first_name .

Can we use aggregate function in ORDER BY clause in SQL?

An aggregate function cannot be used directly in: an ORDER BY clause. Attempting to do so generates an SQLCODE -73 error. However, you can use an aggregate function in an ORDER BY clause by specifying the corresponding column alias or selectItem sequence number.

Can we write AVG in WHERE clause?

This query throws an error, because you cannot use AVG() in a WHERE condition. Since AVG() is a group function, you can only use it in a SELECT statement or in a HAVING clause.

Can we use function in ORDER BY clause?

The ORDER BY clause is not valid in views, inline functions, derived tables, and subqueries, unless either the TOP or OFFSET and FETCH clauses are also specified. When ORDER BY is used in these objects, the clause is used only to determine the rows returned by the TOP clause or OFFSET and FETCH clauses.


1 Answers

To sort on the average of Field1 + Field2 + Field3 you can either add a new field and sort on that.

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

Or you can put your query in a sub-query and sort on the sum of the fields in the outer query.

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
like image 114
Mikael Eriksson Avatar answered Oct 12 '22 12:10

Mikael Eriksson