gpt4 book ai didi

postgresql - 为内置聚合函数创建别名

转载 作者:行者123 更新时间:2023-11-29 13:21:55 24 4
gpt4 key购买 nike

我正在使用 Postgres 对托管数据库进行本地测试。托管数据库有几个 Postgres 中不存在的功能。我不需要复制这些函数,但我需要能够调用具有相同名称的函数并得到合理的答案。例如,我想将计数函数别名为 approximate_count_distinct。一个示例查询是:

     select approximate_count_distinct(id)
from table;

此查询的行为与计数完全相同。我不需要担心它与托管数据库不完全相同这一事实

我查看了 CREATE AGGREGATE,但无法获得正确的参数。这是我为 CREATE AGGREGATE 尝试做的事情:

   CREATE AGGREGATE approximate_count_distinct(*) 
(
sfunc = count,
stype = bigint,
initcond = 0
);

但它没有编译,因为它说错误:函数 count(bigint) 不存在

我试图找到声明此函数的正确方法,但无可救药地迷路了。我查看了 pg_proc,但似乎以一种奇怪的方式将 count 定义为 aggregate_dummy 作为 src 符号链接(symbolic link)。

我查看了 ALIAS FOR 但这似乎不起作用。

长话短说,我不知道该怎么做才能让它发挥作用。肯定有一种简单的方法可以做到这一点?

最佳答案

使用count(*)聚合的声明,只是改个名字:

create aggregate approximate_count_distinct(*) (
sfunc = int8inc,
stype = int8,
initcond = '0'
);

select count(*), approximate_count_distinct(*)
from generate_series(1, 100)

count | approximate_count_distinct
-------+----------------------------
100 | 100
(1 row)

您可以使用伪类型 anyelement 作为参数的泛型类型:

create aggregate approximate_count_distinct(anyelement) (
sfunc = int8inc_any,
stype = int8,
initcond = '0'
);

select
approximate_count_distinct(id::int) as int,
approximate_count_distinct(id::dec) as dec,
approximate_count_distinct(id::text) as text
from generate_series(1, 100) id

int | dec | text
-----+-----+------
100 | 100 | 100
(1 row)

关于postgresql - 为内置聚合函数创建别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40268575/

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