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
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 .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With