【问题标题】:Only select type int in a column?仅在列中选择类型 int?
【发布时间】:2014-08-01 21:57:35
【问题描述】:

我希望只选择可以平均的列。 (Int 是我唯一知道的,但如果还有其他人,我想知道。

select avg(case when <column> = int then <column> else 0 end)

这是我会尝试的,但它似乎不起作用。当我尝试这个时:

Select Avg(<column>) as <alias>

上面写着:

ERROR: function avg(double precision) does not exist

我想我可能需要将此添加到 join 语句中的 from 子句中,但我不确定如何执行此操作。

【问题讨论】:

  • Ave 应该是什么? Postgres 的平均聚合函数是 avg
  • @ErwinBrandstetter 可能就是这样。我检查了eclipse,它的聚合是ave,所以我认为查询是一样的。我将对其进行编辑,并将问题留给需要帮助解决类似问题的人。

标签: sql postgresql types int aggregate-functions


【解决方案1】:

平均的 Postgres 聚合函数是 avg(),适用于一系列数字类型包括 double precision。特别是per documentation:

smallint、int、bigint、实数、双精度、数字或区间

您可以使用pg_typeof() 来确定任何值(或列)的实际数据类型。

识别列

致...select only the columns that I can average:

SELECT attname, atttypid::regtype::text
FROM   pg_attribute
WHERE  attrelid = 'tbl'::regclass
AND    atttypid = ANY ('{int2,int,int8,real,float8,numeric,interval}'::regtype[])
AND    attnum > 0
AND    NOT attisdropped
ORDER  BY attnum;

动态计算

动态确定列的类型是否具有聚合依赖于它并非易事。
这会起作用(不包括特殊情况interval):

SELECT avg(CASE WHEN pg_typeof(t_int) = ANY ('{int2,int,int8,real,float8,numeric}'::regtype[])
           THEN t_int::numeric ELSE NULL::numeric END) AS avg_t_int
      ,avg(CASE WHEN pg_typeof(t_num) = ANY ('{int2,int,int8,real,float8,numeric}'::regtype[])
           THEN t_num::numeric ELSE NULL::numeric END) AS avg_t_num
      ,avg(CASE WHEN pg_typeof(t_txt) = ANY ('{int2,int,int8,real,float8,numeric}'::regtype[])
           THEN t_txt::numeric ELSE NULL::numeric END) AS avg_t_txt
FROM tbl;

SQL Fiddle 演示两者。

对于大表,在动态组合语句之前检查列类型会更有效...

【讨论】:

    【解决方案2】:

    表达式

    regexp_replace(val, '\d', '', 'g')
    

    如果val 只包含数字,则给出空字符串,所以

    select case regexp_replace(val, '\d', '', 'g') 
        when '' then val::int 
        else null end
    

    如果val代表无符号整数,则给出整数值,否则为null。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      • 2019-07-13
      • 2012-05-25
      • 2011-06-22
      相关资源
      最近更新 更多