简体   繁体   中英

Parametrizing output of a select statement PSQL

I am on a version of postgresql that was built off 8.3. 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:

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;

The problem is the above query does not return the output of the select statement in a table format I am used to. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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