Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avg of a Sum in one query

I would like to know if I can get the average of a sum in one single SQL SERVER request,

Have tried to do it with the following request but it doesn't work:

  SELECT t.client,           AVG(SUM(t.asset)) AS Expr1     FROM TABLE t GROUP BY t.client 
like image 660
Roch Avatar asked Oct 15 '09 14:10

Roch


People also ask

Can we use AVG and SUM together in SQL?

In SQL, there are two built-in functions to sum or average the data in your table. In this article I will show you how to use the SUM and AVG functions in SQL using code examples.

How do you calculate average in SQL query?

The avg() function has the following syntax: SELECT AVG( column_name ) FROM table_name; The avg() function can be used with the SELECT query for retrieving data from a table.

How do you use SUM and count together in SQL?

SUM() and COUNT() functionsSUM of values of a field or column of a SQL table, generated using SQL SUM() function can be stored in a variable or temporary column referred as alias. The same approach can be used with SQL COUNT() function too.

What is the purpose of SUM () and AVG ()?

In SQL, SUM() and AVG() functions are used to calculate total and average values in numeric columns.


2 Answers

I think your question needs a bit of explanation. If you want to take the sums grouped by t.client you can use:

SELECT t.client, SUM(t.asset) FROM the-table t GROUP BY t.client 

Then, if you want to take the average of this sume, just make:

SELECT AVG(asset_sums) FROM (     SELECT t.client, SUM(t.asset) AS asset_sums     FROM the-table t     GROUP BY t.client ) as inner_query 

You can't however group the outer query, because this will give you results like in the first query. The results from the inner query are already grouped by t.client.

like image 190
Lukasz Lysik Avatar answered Oct 23 '22 15:10

Lukasz Lysik


Its very simple

for ex.

 SELECT t.client,           SUM(t.asset)/count(t.asset) AS average     FROM TABLE t GROUP BY t.client 

in "average" you will get average of "t.asset"

like image 42
Kalpesh Gohel Avatar answered Oct 23 '22 17:10

Kalpesh Gohel