admin管理员组文章数量:1122832
I am using snowflake to get some data. I have one requirement that i want to extract year_month_day from a string.
a string would be 'IN_2001_02_23_guid' and I want to extract 20010223 from this string.
Could you please help me to find this?
Thank you.
I am using snowflake to get some data. I have one requirement that i want to extract year_month_day from a string.
a string would be 'IN_2001_02_23_guid' and I want to extract 20010223 from this string.
Could you please help me to find this?
Thank you.
Share Improve this question asked Nov 21, 2024 at 11:48 SaloniSaloni 5272 gold badges13 silver badges31 bronze badges 1- You could also try substr and get the date, select to_date(substr('IN_2001_02_23_guid' ,4,10) , 'YYYY_MM_DD') from dual; – Himanshu Kandpal Commented Nov 21, 2024 at 13:51
2 Answers
Reset to default 2@Dave's answer is probably the best for your use case if the pattern is well defined.Otherwise REGEXP_SUBSTR
can be used for cases when it is needed to extract a substring that matches a regular expression pattern.
Please note : This function doesn't modify the string; it simply returns the part of the string that matches the pattern.
Solution using REGEXP_SUBSTR :
SELECT REGEXP_SUBSTR('IN_2001_02_23_guid', '\\d+', 1, 1) ||
REGEXP_SUBSTR('IN_2001_02_23_guid', '\\d+', 1, 2) ||
REGEXP_SUBSTR('IN_2001_02_23_guid', '\\d+', 1, 3) AS extracted_date;
Explanation :
\\d+ represents digits
REGEXP_SUBSTR('IN_2001_02_23_guid', '\\d+', 1, 1) -- 1,1 means start from position 1 and pick up the first match i.e 2001
REGEXP_SUBSTR('IN_2001_02_23_guid', '\\d+', 1, 2) -- 1,2 means start from position 1 and pick up the second match i.e 02
REGEXP_SUBSTR('IN_2001_02_23_guid', '\\d+', 1, 3) -- 1,3 means start from position 1 and pick up the third match i.e 23
If your format will always be similar to the example, the easy way is to replace all characters that are not digits with '' using REGEXP_REPLACE
.
select regexp_replace(val,'[^0-9]','') as y_m_d from tbl;
Y_M_D |
---|
20010223 |
本文标签: how to find yearmonthdate from a string in snowflakeStack Overflow
版权声明:本文标题:how to find year_month_date from a string in snowflake - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736311195a1934653.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论