0

我使用的是基于 8.3 构建的 postgresql 版本。我基于特定的 IP 地址运行了大量查询,并希望创建一个函数,我可以将 IP 地址作为参数传递,类似于:

CREATE OR REPLACE FUNCTION features.src_forensics(text)     
RETURNS SETOF rows as
$$

select src, action,
count(distinct date_trunc('day', receive_time) ) n_activeDay,
count(distinct source_IP) n_src,
count(distinct source_IP) / count(distinct date_trunc('day', receive_time)) n_src_per_day,
sum(bytes) as total_bytes,
min(receive_time) minTime,
max(receive_time) maxTime
from  table
where src = $1 
group by src, action ;

$$ 语言 sql;

问题是上面的查询没有以我习惯的表格格式返回 select 语句的输出。如果我将 10.10.0.1 作为 IP 地址输入传递给函数,如何让上面编写的脚本表现得像下面的 select 语句?

select src, action,
count(distinct date_trunc('day', receive_time) ) n_activeDay,
count(distinct source_IP) n_src,
count(distinct source_IP) / count(distinct date_trunc('day', receive_time)) n_src_per_day,
sum(bytes) as total_bytes,
min(receive_time) minTime,
max(receive_time) maxTime
from  table
where src = '10.10.0.1'
group by src, action;
4

1 回答 1

1

我通常在返回任意一组列时这样做:

RETURNS TABLE(
    src             text,
    action          text,
    n_activeDay     bigint,
    n_src           bigint,
    n_src_per_day   bigint,
    total_bytes     bigint,
    minTime         timestamptz,
    maxTime         timestamptz
) AS

如果您希望保持定义不变,则可以更改查询函数的方式:

select * from features.src_forensics("a") AS f(
        src             text,
        action          text,
        n_activeDay     bigint,
        n_src           bigint,
        n_src_per_day   bigint,
        total_bytes     bigint,
        minTime         timestamptz,
        maxTime         timestamptz
    );
于 2013-02-19T19:28:55.960 回答