How to round to nearest X minutes with PL/pgSQL?

后端 未结 7 1472
伪装坚强ぢ
伪装坚强ぢ 2021-01-07 03:36

How I can round to nearest X minutes?

Here\'s my attempt:

DECLARE
  _stamp ALIAS FOR $1; -- timestamp
  _nearest ALIAS FOR $2; -- minutes (integer)
         


        
7条回答
  •  有刺的猬
    2021-01-07 03:46

    Further to my previous answer, here's a function that puts it all together and does exactly what you ask for:

    CREATE FUNCTION date_round(base_date timestamptz, round_interval interval)
        RETURNS timestamptz AS $BODY$
    SELECT '1970-01-01'::timestamptz 
        + (EXTRACT(epoch FROM $1)::integer + EXTRACT(epoch FROM $2)::integer / 2)
        / EXTRACT(epoch FROM $2)::integer
        * EXTRACT(epoch FROM $2)::integer * interval '1 second';
    $BODY$ LANGUAGE SQL STABLE;
    

    And here's an example of calling it:

    SELECT date_round(now(), '15 minutes');
    

    You can supply any interval you want and it should work. As coded it rounds to the nearest interval, either up or down.

    If you wanted to truncate instead then just remove the + EXTRACT(epoch FROM $2)::integer / 2).

    Hopefully this will now act as a definitive answer that accepts the correct argument types (interval rather than integer number of minutes).

提交回复
热议问题