[英]Parametrizing output of a select statement PSQL
I am on a version of postgresql that was built off 8.3. 我使用的是基于8.3构建的postgresql版本。 I run a ton of queries based on specific Ip address and wanted to create a function that I can pass the IP address as a parameter similar to:
我基于特定的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; $$ LANGUAGE sql;
The problem is the above query does not return the output of the select statement in a table format I am used to. 问题是上面的查询没有以我惯用的表格式返回select语句的输出。 How do I get the script I wrote above to behave like the select statement below if I pass 10.10.0.1 as the IP address input to the function?
如果将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;
I generally do this when returning an arbitrary set of columns: 我通常在返回任意列集时执行此操作:
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
It may be possible to change how you query the function, if you prefer leaving the definition unchanged: 如果您希望保留定义不变,则可以更改查询函数的方式:
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.