选择整个表中两列之间的平均值

时间:2016-01-19 20:10:46

标签: mysql average

我有一张桌子(例如):

price_from price_to
10 100
20 60
0 70
30 0

我正在寻找在每行中选择数字与数字之间的平均值以及结果值的平均值的方法。 谢谢!

2 个答案:

答案 0 :(得分:4)

每行的price_from和price_to的平均值:

SELECT (price_from + price_to) / 2 AS row_avg FROM tablename;

上述每行平均值的平均值:

SELECT AVG((price_from + price_to) / 2) AS avg_of_avgs FROM tablename;

每列的平均值:

SELECT AVG(price_from) AS price_from_avg, AVG(price_to) AS price_to_avg FROM tablename;

所有数据的平均值(price_from和price_to):

SELECT AVG(p) as total_avg FROM 
(SELECT price_from AS p FROM tablename UNION ALL SELECT price_to FROM tablename) dummyname;

如果price_from和price_to都是整数,则上述查询将返回整数平均值。如果您想要在这种情况下的小数平均值,则需要使用强制转换来转换为每个列计算中至少有一个数字给浮点数。然后查询将成为:

每行的price_from和price_to的平均值(带有强制转换):

SELECT ( CAST(price_from AS FLOAT) + price_to ) / 2 AS row_avg FROM tablename;

以上每个行平均查询的平均值(带有强制转换):

SELECT AVG( ( CAST(price_from AS FLOAT) + price_to ) / 2 ) AS avg_of_avgs FROM tablename;

每列的平均值(带演员表):

SELECT AVG( CAST(price_from AS FLOAT) ) AS price_from_avg, 
AVG( CAST(price_to AS FLOAT) ) AS price_to_avg FROM tablename;

所有数据的平均值(price_from和price_to都带有强制转换):

SELECT AVG(p) as total_avg FROM
(SELECT CAST(price_from AS FLOAT) AS p FROM tablename UNION ALL 
SELECT CAST(price_to AS FLOAT) FROM tablename) dummyname;

答案 1 :(得分:1)

尝试此查询

SELECT AVG(avgprice) as avgprice from 
(SELECT (price_from + price_to) / 2 AS avgprice FROM [Table Name]) as temp;