如何四舍五入到最接近的 X 分钟?
这是我的尝试:
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;
例子:
SELECT round_to_nearest_minute ('2010-01-01 12:34:56', 15);
应该返回
2010-01-01 12:30:00