如何从日期列为 varchar 数据类型的日期中获取月份。仅供参考,使用雪花工具

How to fetch month from date where date column is in varchar datatype. FYI using snowflake tool

如何从日期列为 varchar 数据类型的日期中获取月份。仅供参考,使用雪花工具。 例如,如果我想要 6 月份的数据?我怎样才能取到?

您必须在 snowflake 中使用 to_date 将 varchar 数据类型转换为日期,如下所示

select *
from yourTable
where to_date(yourDateColumn, 'YYYY-MM-DD') >= '2020-06-01'
and to_date(yourDateColumn, 'YYYY-MM-DD') <= '2020-06-30'

首先,您不应该将日期存储为字符串。但你可能知道。

如果您确实将日期存储为字符串,则将它们全部存储为一种特定格式,例如 'mm/dd/yyyy'。因此,使用 substring 函数获取月份数字。

对于'mm/dd/yyyy'

where substring(date_string, 1, 2) = '06'

对于'yyyy-mm-dd'

where substring(date_string, 9, 2) = '06'

在很多情况下你也可以使用LIKE:

对于'mm/dd/yyyy'

where date_string like '06%'

对于'yyyy-mm-dd'

where date_string like '%-06-%'

您可以使用 TO_DATE(…) function to treat the VARCHAR column as a formatted date type, and the EXTRACT(…) function 只检索日期中的月份。

如果您的日期字符串以众所周知的方式格式化,TO_DATE 的自动解析(或 direct cast using the :: operator)就足够了,您可以这样编写查询:

SELECT * FROM table
WHERE
    EXTRACT(month, TO_DATE(varcharCol)) = 6     -- June of every year
AND EXTRACT(year,  varcharCol::DATE)    = 2020; -- June of 2020 alone

或者,如果日期是非标准格式,use available formatting options 使 TO_DATE(…) 正确解析它:

-- Dates of custom format, such as: 'June # 02 # 2020'
SELECT
    EXTRACT(month, TO_DATE(varcharCol, 'MMMM # DD # YYYY')) AS month
FROM table
WHERE
    month = 6;

注意:如果数据中包含完整的时间戳值,您还可以将上面的所有 DATETO_DATE 替换为 TIMESTAMP and TO_TIMESTAMP而不仅仅是一个日期。