EXTRACT 函数
EXTRACT 函数从 TIMESTAMP 值或表达式 TIME 或 TIMETZ 中返回日期或时间部分,例如日、月或年、小时、分钟、秒、毫秒或微秒。
语法
EXTRACT ( datepart FROM { TIMESTAMP 'literal' | timestamp | time | timetz } )
Arguments
- datepart
-
有关可能的值,请参阅日期或时间戳函数的日期部分。
- 文本
-
一个时间戳值,用单引号括起来,前面有 TIMESTAMP 关键字。
- timestamp | times | timestz
-
TIMESTAMP、TIMESTAMPTZ、TIME 或 TIMETZ 列或隐式转换为 TIMESTAMP、TIMESTAMP WITH TIME ZONE、TIME 或 TIMETZ 的表达式。
返回类型
如果参数是 TIMESTAMP、TIME 或 TIMETZ,则为 INTEGER
如果参数是 TIMESTAMPTZ,则为 DOUBLE PRECISION
具有时间戳列的示例
以下示例确定支付价格为 10000 美元或更高的销售周数。
select salesid, extract(week from saletime) as weeknum from sales where pricepaid > 9999 order by 2; salesid | weeknum --------+--------- 159073 | 6 160318 | 8 161723 | 26 (3 rows)
以下示例从文本时间戳值返回分钟值。
select extract(minute from timestamp '2009-09-09 12:08:43'); date_part ----------- 8 (1 row)
具有时间列的示例
下面的示例表 TIME_TEST 具有一个列 TIME_VAL(类型 TIME),其中插入了三个值。
select time_val from time_test; time_val --------------------- 20:00:00 00:00:00.5550 00:58:00
以下示例从每个 time_val 中提取分钟数。
select extract(minute from time_val) as minutes from time_test; minutes ----------- 0 0 58
以下示例从每个 time_val 中提取小时数。
select extract(hour from time_val) as hours from time_test; hours ----------- 20 0 0
以下示例从文本值中提取毫秒。
select extract(ms from time '18:25:33.123456'); date_part ----------- 123
具有 TIMETZ 列的示例
下面的示例表 TIMETZ_TEST 具有一个列 TIMETZ_VAL(类型 TIMETZ),其中插入了三个值。
select timetz_val from timetz_test; timetz_val ------------------ 04:00:00+00 00:00:00.5550+00 05:58:00+00
以下示例从每个 timetz_val 中提取小时数。
select extract(hour from timetz_val) as hours from time_test; hours ----------- 4 0 5
以下示例从文本值中提取毫秒。在处理提取之前,文本不会转换为 UTC。
select extract(ms from time '18:25:33.123456 EST'); date_part ----------- 123