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

后端 未结 7 1520
伪装坚强ぢ
伪装坚强ぢ 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:53

    This seems to work:

    DECLARE
      _stamp ALIAS FOR $1;
      _nearest ALIAS FOR $2;
      _seconds integer;
      _ret timestamp;
      _minutes decimal;
      _mod decimal;
    BEGIN
      _ret := date_trunc('minute', _stamp);
    
      SELECT EXTRACT (minute FROM _ret)::integer INTO _minutes;
    
      _mod := _minutes % _nearest;
    
      IF (_mod > (_nearest / 2)) THEN
        RETURN _ret + (_nearest - _mod) * interval '1 minute';
      ELSE
        RETURN _ret - (_mod) * interval '1 minute';
      END IF;
    
      RETURN _ret;
    
    END;
    

    Thanks to Stephen Denne :)

提交回复
热议问题