【PGSQL】date_trunc 函数

date_trunc 函数用于在 PostgreSQL 中将日期或时间戳值截断(向下取整)到指定的精度级别。当您想要忽略较小的时间单位(例如,小时、分钟、秒),专注于较大的单位(例如,天、月、年)时,该函数非常有用。date_trunc 的语法如下:

date_trunc(unit, source);

  • unit:指定要将源值截断到的时间单位。可以是以下之一:
    • 'microseconds'(微秒)
    • 'milliseconds'(毫秒)
    • 'second''seconds'(秒)
    • 'minute''minutes'(分钟)
    • 'hour''hours'(小时)
    • 'day''days'(天)
    • 'week''weeks'(周)
    • 'month''months'(月)
    • 'quarter''quarters'(季度)
    • 'year''years'(年)

通过指定 unit,您可以将 source 的值截断到所需的时间精度。以下是一些示例:

-- 将时间戳截断到小时 
SELECT date_trunc('hour', TIMESTAMP '2024-01-16 14:32:45'); 

-- 将日期截断到月 
SELECT date_trunc('month', DATE '2024-01-16'); 

-- 将时间戳截断到季度 
SELECT date_trunc('quarter', TIMESTAMP '2024-01-16 14:32:45');

这些查询将返回截断到指定单位的日期或时间戳。

你可能感兴趣的:(数据库)