gpt4 book ai didi

sql - 仅在列中选择类型 int?

转载 作者:行者123 更新时间:2023-11-29 14:21:32 25 4
gpt4 key购买 nike

我希望只选择可以平均的列。 (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

我在想我可能需要将它添加到连接语句中的 from 子句中,但我不确定该怎么做。

最佳答案

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

smallint, int, bigint, real, double precision, numeric, or interval

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

识别列

要... 仅选择我可以平均的列:

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证明两者。

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

关于sql - 仅在列中选择类型 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24169774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com