Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL aggregate function over range

I am trying to create a function that will find the intersection of tsrange, but I can't get it work:

CREATE AGGREGATE intersection ( tsrange ) (
    SFUNC = *,
    STYPE = tsrange
)
like image 831
Alex V Avatar asked Jul 01 '26 19:07

Alex V


1 Answers

There are two modifications to your attempt. First, I don't think you can use an operator as the SFUNC, so you need to define a named function to do the intersection, and use that.

CREATE or REPLACE FUNCTION int_tsrange(a tsrange, b tsrange)
   returns tsrange language plpgsql as 
      'begin return a * b; end';

Secondly, the default value for a range is the empty range -- so the intersection will always be empty. You need to initialize the range to an infinite range '[,]' to begin the aggregate. The aggregate definition then looks like:

CREATE AGGREGATE intersection ( tsrange ) (
    SFUNC = int_tsrange,
    STYPE = tsrange,
    INITCOND = '[,]'
);
like image 195
Robert M. Lefkowitz Avatar answered Jul 04 '26 01:07

Robert M. Lefkowitz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!