如何计算,添加和查找SQL中三列的平均值?

时间:2017-11-23 11:55:39

标签: sql oracle11g

我正在尝试计算三列的元素,添加它们并绘制一个点或位置的列车数量的平均值。

示例表

  Localizaton  | Numbers_trains|  Engine_1 |  Engine_2| Engine_3
    A          |  4            |    2      |   4      |  4
    A          |  12           |    3      |   1      |  8
    B          |  43           |    2      |   3      |  9
    B          |  45           |    3      |   5      |  3 
    B          |  23           |    5      |   6      |  2
    C          |  54           |    7      |   8      |  3

我的想法是做类似的事情:

Value_1 AS E1,
Value_2 AS E2,
Value_3 AS EC3
sum (count (E1) + count (E2) + count (E3) ) AS TOTAL
AVG (TOTAL/ Numbers_trains) AS Average

结果是获得:

  Localizaton  |    AVG        |
    A          |  4            |    
    A          |  13           |    
    B          |  4,5          |    
    B          |  10           |  
    B          |  2,5          |   
    C          |  5,4          |

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

注意:我没有添加GROUP BY声明,因为SELECT仅包含群组功能(例如SUMCOUNT

SELECT SUM(engine_1) AS sum_e1
     , SUM(engine_2) AS sum_e2
     , SUM(engine_3) AS sum_e3
     , (SUM(engine_1) + SUM(engine_2) + sum(engine_3)) AS sum_e_total
     , COUNT(*) AS count_total
     , (SUM(engine_1) + SUM(engine_2) + sum(engine_3)) / COUNT(*) AS avg_e
  FROM [table_name]

修改

在您编辑之后 - 认为这应该有效:

SELECT Localization
     , SUM(Number_trains) AS sum_num_trains
     , SUM(Engine_1) AS sum_e1
     , SUM(Engine_2) AS sum_e2
     , SUM(Engine_3) AS sum_e3
     , (SUM(Engine_1) + SUM(Engine_2) + SUM(Engine_3)) AS sum_e_total
     , COUNT(*) AS count_total
     , (SUM(Engine_1) + SUM(Engine_2) + SUM(Engine_3)) / COUNT(*) AS avg_e
  FROM [table_name]
 GROUP BY Localization
 ORDER BY Localization ASC

修改2

获取COUNT([Engine_])

SELECT Localization
     , SUM(Number_trains) AS sum_num_trains
     , SUM(Engine_1) AS sum_e1
     , COUNT(Engine_1) AS count_e1
     , SUM(Engine_2) AS sum_e2
     , COUNT(Engine_2) AS count_e2
     , SUM(Engine_3) AS sum_e3
     , COUNT(Engine_3) AS count_e3
     , (SUM(Engine_1) + SUM(Engine_2) + SUM(Engine_3)) AS sum_e_total
     , COUNT(*) AS count_total
     , (SUM(Engine_1) + SUM(Engine_2) + sum(Engine_3)) / COUNT(*) AS avg_e
  FROM [table_name]
 GROUP BY Localization
 ORDER BY Localization ASC

注意:您不需要 来提取sum_e1sum_e2等 - 我刚刚添加它们用于演示目的。

查看有关GROUP函数的文章:

http://beginner-sql-tutorial.com/sql-group-functions.htm

编辑3

获得您想要的结果! 希望 ...

平均引擎 本地化和列车数量。

SELECT Localization
     , Number_trains
     , (SUM(Engine_1) + SUM(Engine_2) + SUM(Engine_3)) / COUNT(*) AS avg_e
  FROM [table_name]
 GROUP BY Localization
     , Number_trains
 ORDER BY Localization ASC
     , Number_trains ASC