【问题标题】:How to find the average of a columnn which has string and numerical values?如何找到具有字符串和数值的列的平均值?
【发布时间】:2019-06-15 16:35:16
【问题描述】:

我想计算两列的平均值,但每列之间都有字符串值,并且在应用 avg 函数时会产生错误。我该如何解决这个问题?

【问题讨论】:

  • 请分享您的代码
  • 您可以添加一个 where 子句,指示列值应该是数字
  • edit您的问题包含minimal reproducible example,其中包含:一些示例数据;您对该样本数据的预期输出;关于如何获得预期输出的英文描述(如果不明显);您对解决方案的尝试;以及它生成的错误消息。

标签: sql oracle


【解决方案1】:

这可能有效

Select (cast(col1 as float) + cast(col2 as float)) / 2 as average_between_col1_and_col2, 
        avg(cast(col2 as float)) as avg_col_2, 
        avg(cast(col1 as float)) as avg_col_1
from table tbl

无论如何,请提供一个完整的示例,其中包含示例数据、您执行的期望结果查询以及您遇到的错误。

注意,我的查询假定两列都不是数字而是包含数字,如果一列已经是数字,则可以省略强制转换。

【讨论】:

    【解决方案2】:

    样本数据会有所帮助;我不确定您说要“计算平均两列”是什么意思-是(COLUMN_1 + COLUMN_2) / 2 还是AVG(COLUMN_1)AVG(COLUMN_2)

    不管怎样,原理都是一样的——检查列是否包含数字并进行计算。否则,什么也不做。例如:

    SQL> with test (col1, col2) as
      2    (select 'a2' , 'ccc' from dual union all
      3     select '100', '200' from dual union all
      4     select '15' , 'xx'  from dual
      5    )
      6  select col1,
      7         col2,
      8         case when regexp_like(col1, '^\d+$') and regexp_like(col2, '^\d+$') then
      9                   (to_number(col1) + to_number(col2)) / 2
     10              else null
     11         end average
     12  from test;
    
    COL COL    AVERAGE
    --- --- ----------
    a2  ccc
    100 200        150
    15  xx
    
    SQL>
    

    【讨论】:

      【解决方案3】:

      如果您想要每列中的总体平均值,那么:

      select avg(case when col1 like '^\d+$' then to_number(col1) end) as avg_col1,
             avg(case when col2 like '^\d+$' then to_number(col2) end) as avg_col2
      from t;
      

      avg() 忽略 NULL 值。

      如果你想要一行内的平均值,那么avg() 是不合适的(它是一个聚合函数)。在这种情况下:

      select (case when col1 like '^\d+$' and col2 like '^\d+$'
                   then ( to_number(col1) + to_number(col2) ) / 2
                   when col1 like '^\d+$'
                   then to_number(col2)
                   when col2 like '^\d+$'
                   then to_number(col1)
              end) as avg_col1_2
      from t;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-30
        • 1970-01-01
        相关资源
        最近更新 更多