背景描述
Postgresql中不支持round(date)函数,使用plpgsql做补齐。
原理与解决方案
Oracle中round(date)实现的功能是四舍五入到指定的单位上。
在Postgresql中使用date_trunc,但是只能把时间做截断,所以在实现时需要先做偏移再做截断,实现四舍五入的效果。
代码语言:javascript复制date_trunc(text, timestamp)
return: timestamp
实现
代码语言:javascript复制CREATE OR REPLACE FUNCTION round(timestamp, text)
RETURNS timestamp AS
$m$
DECLARE
r timestamp;
BEGIN
IF $2 = 'minute' THEN
SELECT date_trunc($2, $1 interval '30 second') INTO r;
ELSIF $2 = 'hour' THEN
SELECT date_trunc($2, $1 interval '30 minute') INTO r;
ELSIF $2 = 'day' THEN
SELECT date_trunc($2, $1 interval '12 hour') INTO r;
ELSIF $2 = 'week' THEN
SELECT date_trunc($2, $1 interval '84 hour') INTO r;
ELSIF $2 = 'month' THEN
SELECT date_trunc($2, $1 interval '15 day') INTO r;
ELSIF $2 = 'year' THEN
SELECT date_trunc($2, $1 interval '6 month') INTO r;
ELSE
RAISE EXCEPTION 'timestamp units "%" not recognized, please contact DBA', $2;
END IF;
RETURN r;
END;
$m$ LANGUAGE plpgsql;
效果
代码语言:javascript复制select round(timestamp '2015-07-10 11:52:30.000', 'year');
2016-01-01 00:00:00
select round(timestamp '2015-07-10 11:52:30.000', 'hour');
2015-07-10 12:00:00
select round(timestamp '2015-07-10 11:52:30.000', 'minute');
2015-07-10 11:53:00