简体   繁体   中英

How to properly calculate averages in SQL

For things such as revenue per employee, or selling price per product

Which method would be correct, and are there cases where one will work and the other won't?

SUM(revenue)/SUM(employee)

/* OR */

AVG(revenue/employee)

I have been getting different answers with the above.

Without knowing your table structure it's difficult to know what's appropriate for you.

SUM(revenue)/SUM(employee) will just divide sum of all revenues by sum of employees (Or it can be count).

Where as AVG(revenue/employee) will sum all the revenue/employee then divide the result by number of rows.

For your purpose I think first method will be appropriate.

The two are doing two very different things. One is calculating an overall average (the first one). The second is calculating a weighted average treating each row separately.

As a simple example, consider a small table:

employees      revenue
 99               99
  1              100

The first returns (100 + 99) / 100 = 1.99 . This would be the same average if you had a table with 100 rows, one per "employee" and the revenue were revenue / employee (ie 1 on 99 rows and 100 on 1 row).

The second returns (99 / 99) + (100 / 1) = 101. This would be treating each row "equally". That is, it is a biased average. Sometimes this is useful, but not usually for counts. For instance, it might be useful for rates of some sort. Or it might be useful if the sizes on the rows are roughly the same.

In general, you would want the first format under most circumstances, based on the limited information in your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM