Snowflake中如何从无时区的timestamp字段提取月份
无时区timestamp类型字段提取月份解决方案
报错原因
date_part函数的第一个参数为标识时间单位的字符串,必须使用单引号包裹。未加引号时数据库会将month识别为列名进行检索,因此触发列不存在的报错。
可用实现方案
- 方案1:修正
date_part函数语法,提取数字格式月份
SELECT nameofthecolum, date_part('month', nameofthecolum) AS month_number FROM tablename;
- 方案2:使用适配性更高的
EXTRACT函数,无需给时间单位加引号
SELECT nameofthecolum, EXTRACT(MONTH FROM nameofthecolum) AS month_number FROM tablename;
- 若需提取月份名称(如January、一月),可直接使用
to_char函数处理无时区timestamp,无需提前转换为带时区类型:
-- 输出英文月份全称 SELECT nameofthecolum, to_char(nameofthecolum, 'FMMonth') AS month_name_en FROM tablename; -- PostgreSQL环境输出中文月份全称示例 SELECT nameofthecolum, to_char(nameofthecolum, 'FMMonth', 'lcc_time=zh_CN.UTF-8') AS month_name_cn FROM tablename;
内容的提问来源于stack exchange,提问作者magicdragongirl
相关产品推荐
相关产品推荐

