0

I basically have a pretty complicated view that currently returns what I want from last-week aggregations.

SELECT *
FROM ...
WHERE  t1.event_date >= ('now'::text::date - 7) 
...

Now I'd like to be able to make the same calculations for any given 2 dates, so I want to be able to pass parameters to my view. Pretty much I want to replace the WHERE clause with something like:

WHERE  t1.event_date BETWEEN %first date% AND %second_date%

I think I should be able to do this with a set returning function but can't figure exactly how to do it. Any ideas?

1 Answer 1

1

Create a function (sometimes called table-function, when returning a set of rows). There are many (procedural) languages, in particular PL/pgSQL. In your case LANGUAGE sql does the job:

CREATE OR REPLACE FUNCTION get_user_by_username(d1 date, d2 date)
  RETURNS TABLE ( ... )
  LANGUAGE sql AS
$func$
SELECT ...
WHERE  t1.event_date >= $1
AND    t1.event_date <  $2  -- note how I exclude upper border
$func$;

Example for LANGUAGE sql:

Examples for LANGUAGE plpgsql:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.