繁体   English   中英

参数化选择语句PSQL的输出

[英]Parametrizing output of a select statement PSQL

我使用的是基于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 ;

$$ LANGUAGE 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;

我通常在返回任意列集时执行此操作:

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
    );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM