- 类别:
TRUNC¶
将 DATE、TIME 或 TIMESTAMP 值截断为指定的精度。例如,将时间戳截断到季度时,将返回对应于原始时间戳季度第一天午夜的时间戳。
该函数通过反转两个实参,为 DATE_TRUNC 提供了另一种语法。
截断与提取不同。例如:
使用此函数将时间戳截断为季度,会返回与输入时间戳所在季度第一天的午夜相对应的时间戳。
使用 EXTRACT 函数从时间戳中提取季度日期部分,会返回时间戳中年份的季度编号。
备注
此函数可重载;它也可以用作数值函数来 向下舍入数值表达式。
- 选择:
- 另请参阅:
语法¶
TRUNC( <date_or_time_expr>, <date_or_time_part> )
实参¶
date_or_time_expr
此实参的值必须是日期、时间或时间戳。
date_or_time_part
此实参必须是 支持的日期和时间部分 中列出的值之一。
返回¶
返回值与输入值的类型相同。
例如,如果输入值为 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",
TRUNC(mydate, 'year') AS "TRUNCATED TO YEAR",
TRUNC(mydate, 'month') AS "TRUNCATED TO MONTH",
TRUNC(mydate, 'day') 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",
TRUNC(mytime, 'minute') AS "TRUNCATED TO MINUTE"
FROM test_date_trunc;
+----------+---------------------+
| TIME | TRUNCATED TO MINUTE |
|----------+---------------------|
| 08:50:48 | 08:50:00 |
+----------+---------------------+
将 TIMESTAMP 截断为小时、分钟和秒。
SELECT mytimestamp AS "TIMESTAMP",
TRUNC(mytimestamp, 'hour') AS "TRUNCATED TO HOUR",
TRUNC(mytimestamp, 'minute') AS "TRUNCATED TO MINUTE",
TRUNC(mytimestamp, 'second') 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 TRUNC(mytimestamp, 'quarter') AS "TRUNCATED",
EXTRACT('quarter', mytimestamp) AS "EXTRACTED"
FROM test_date_trunc;
+-------------------------+-----------+
| TRUNCATED | EXTRACTED |
|-------------------------+-----------|
| 2024-04-01 00:00:00.000 | 2 |
+-------------------------+-----------+