【发布时间】:2017-08-22 07:19:32
【问题描述】:
刚开始学习MYSQL,遇到这样的问题
所以表格是这样的:
id name moneySpent
1 Alex 3
2 Alex 1
3 Bill 4
4 Alex 2
5 Alex 1
6 Chris 5
7 Chris 3
假设我想知道人均花费的平均金额。我尝试通过使用 SUM() GROUP BY 和 AVG() 来做到这一点,但我被困在 AVG()
SELECT name, sum(moneySpent) AS total FROM table GROUP BY name;
然后这将返回
name total
Alex 7
Bill 4
Chris 8
那么我怎样才能使用 AVG() 得到 (7+4+8)/3 呢?
【问题讨论】:
-
... union all select 'average', SUM(moneySpent) / count(distinct name) from table