- 类别:
DATE_TRUNC¶
将 DATE、TIME 或 TIMESTAMP 值截断到指定精度。例如,将时间戳截断为季度,会返回对应于原始时间戳季度第一天午夜的时间戳。
该函数通过反转两个实参,为 TRUNC 提供了另一种语法。
截断与提取不同。例如:
使用此函数将时间戳截断为季度,会返回与输入时间戳所在季度第一天的午夜相对应的时间戳。
使用 EXTRACT 函数从时间戳中提取季度日期部分,会返回时间戳中年份的季度编号。
语法¶
DATE_TRUNC( <date_or_time_part>, <date_or_time_expr> )
实参¶
date_or_time_part
此实参必须是 支持的日期和时间部分 中列出的值之一。
date_or_time_expr
此实参的值必须是日期、时间或时间戳。
返回¶
返回值与输入值的类型相同。
例如,如果输入值为 TIMESTAMP,则返回值为 TIMESTAMP。
使用说明¶
当
date_or_time_part
为week
(或其任何变体)时,输出由 WEEK_START 会话参数控制。有关更多详细信息(包括示例),请参阅 日历周和工作日。
示例¶
DATE_TRUNC 函数示例使用了下表中的数据:
CREATE OR REPLACE TABLE test_date_trunc (
mydate DATE,
mytime TIME,
mytimestamp TIMESTAMP);
INSERT INTO test_date_trunc VALUES (
'2024-05-09',
'08:50:48',
'2024-05-09 08:50:57.891 -0700');
SELECT * FROM test_date_trunc;
+------------+----------+-------------------------+
| MYDATE | MYTIME | MYTIMESTAMP |
|------------+----------+-------------------------|
| 2024-05-09 | 08:50:48 | 2024-05-09 08:50:57.891 |
+------------+----------+-------------------------+
以下示例显示了日期截断。在所有情况下,返回值的数据类型与输入值相同,但被截断的部分(如小数秒)为零:
将日期截断为年、月、日:
SELECT mydate AS "DATE",
DATE_TRUNC('year', mydate) AS "TRUNCATED TO YEAR",
DATE_TRUNC('month', mydate) AS "TRUNCATED TO MONTH",
DATE_TRUNC('day', mydate) AS "TRUNCATED TO DAY"
FROM test_date_trunc;
+------------+-------------------+--------------------+------------------+
| DATE | TRUNCATED TO YEAR | TRUNCATED TO MONTH | TRUNCATED TO DAY |
|------------+-------------------+--------------------+------------------|
| 2024-05-09 | 2024-01-01 | 2024-05-01 | 2024-05-09 |
+------------+-------------------+--------------------+------------------+
将时间截断为分钟:
SELECT mytime AS "TIME",
DATE_TRUNC('minute', mytime) AS "TRUNCATED TO MINUTE"
FROM test_date_trunc;
+----------+---------------------+
| TIME | TRUNCATED TO MINUTE |
|----------+---------------------|
| 08:50:48 | 08:50:00 |
+----------+---------------------+
将 TIMESTAMP 截断为小时、分钟和秒。
SELECT mytimestamp AS "TIMESTAMP",
DATE_TRUNC('hour', mytimestamp) AS "TRUNCATED TO HOUR",
DATE_TRUNC('minute', mytimestamp) AS "TRUNCATED TO MINUTE",
DATE_TRUNC('second', mytimestamp) AS "TRUNCATED TO SECOND"
FROM test_date_trunc;
+-------------------------+-------------------------+-------------------------+-------------------------+
| TIMESTAMP | TRUNCATED TO HOUR | TRUNCATED TO MINUTE | TRUNCATED TO SECOND |
|-------------------------+-------------------------+-------------------------+-------------------------|
| 2024-05-09 08:50:57.891 | 2024-05-09 08:00:00.000 | 2024-05-09 08:50:00.000 | 2024-05-09 08:50:57.000 |
+-------------------------+-------------------------+-------------------------+-------------------------+
DATE_TRUNC 函数与 EXTRACT 函数形成鲜明对比:
SELECT DATE_TRUNC('quarter', mytimestamp) AS "TRUNCATED",
EXTRACT('quarter', mytimestamp) AS "EXTRACTED"
FROM test_date_trunc;
+-------------------------+-----------+
| TRUNCATED | EXTRACTED |
|-------------------------+-----------|
| 2024-04-01 00:00:00.000 | 2 |
+-------------------------+-----------+