8

我想从 PostgreSQL 中的一列中计算平均数

SELECT AVG(col_name) 
From TableName

它给了我这个错误:

ERROR: function avg (character varying) does not exist

LINE 1: SELECT AVG(col_name) 
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
4

1 回答 1

10

将数字存储在数字字段、整数、小数或其他任何内容中。但不在 text/varchar 字段中。

检查所有数字数据类型的手册。


讨厌的解决方法:将一些记录转换为数值并将其他记录保留为文本。例子:

/*
create temp table foo AS
SELECT x FROM (VALUES('x'),('1'),('2')) sub(x);
*/

WITH cte AS (
SELECT
    CASE 
        WHEN x ~ '[0-9]' THEN CAST(x AS decimal) -- cast to numeric field
    END AS num,
    CASE 
        WHEN x ~ '[a-zA-Z]' THEN x
    END AS a
FROM foo
)
SELECT AVG(num), COUNT(a) FROM cte;
于 2012-05-02T08:50:19.967 回答