为内置聚合函数创建别名

时间:2016-10-26 17:26:28

标签: postgresql aggregate-functions

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

     select approximate_count_distinct(id)
     from table;

此查询的行为与count完全相同。我不需要担心它与托管数据库上的情况不完全相同

我已经研究过CREATE AGGREGATE,但无法正确获取参数。以下是我尝试为CREATE AGGREGATE做的事情:

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

但它没有编译,因为它说 ERROR: function count(bigint) does not exist

我试图找到正确的方式来声明这个功能,但却毫无希望地失去了。我查看了pg_proc,但是计数似乎以一种奇怪的方式定义为与src符号链接一样的aggregate_dummy。

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

长话短说,我不知道如何使其发挥作用。肯定有一个简单的方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:1)

使用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)