PostgreSQL错误:函数AVG(字符变化)不存在

时间:2012-05-02 08:46:29

标签: postgresql select average

我想计算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.

1 个答案:

答案 0 :(得分:7)

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

查看所有numeric data types的手册。


令人讨厌的工作日:将一些记录转换为数值并将其他记录保存为文本。例如:

/*
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;