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?

Erwin Brandstetter
  • 539,169
  • 125
  • 977
  • 1,137
leonsas
  • 4,536
  • 6
  • 38
  • 67

1 Answers1

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 ( ... ) AS
$body$

SELECT ...
WHERE  t1.event_date >= $1
AND    t1.event_date <  $2  -- note how I exclude upper border

$body$ LANGUAGE sql;

One of many examples for LANGUAGE sql:
Return rows from a PL/pgSQL function

One of many examples for LANGUAGE plpgsql:
PostgreSQL: ERROR: 42601: a column definition list is required for functions returning "record"

Community
  • 1
  • 1
Erwin Brandstetter
  • 539,169
  • 125
  • 977
  • 1,137