How I can round to nearest X minutes?
Here's my attempt:
DECLARE
_stamp ALIAS FOR $1; -- timestamp
_nearest ALIAS FOR $2; -- minutes (integer)
_minutes decimal;
_ret timestamp;
BEGIN
_ret := date_trunc('minute', _stamp);
SELECT EXTRACT (minute FROM _ret)::integer INTO _minutes;
IF (_minutes % _nearest < (_nearest / 2)) THEN
RETURN _ret + _minutes * interval '1 minute';
ELSE
RETURN _ret - _minutes * interval '1 minute';
END IF;
RETURN _ret;
END;
Example:
SELECT round_to_nearest_minute ('2010-01-01 12:34:56', 15);
Should return
2010-01-01 12:30:00
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…