To convert date in Snowflake

允我心安 提交于 2021-02-10 14:32:22

问题


I am trying to work with the date (timestamp to be precise) and getting into trouble. My requirement is below.

I have a stage table where the data is stored as JSON in a Variant Column and the data looks like below in that column.

{
“message_body”: {
“campus_code”: “TEST”,
“campus_name”: “TEST”,
“event_type”: “TEST”,
“location_code”: “A00000”,
“location_name”: “TEST”,
“order”: {
“credit_total”: 0,
“app_version”: “1.0.9”,
“asap”: 1,
“order_datetime”: “2021-01-08 18:19:34”
}
“timezone_offset_minutes”: -360,
}
}

I have below requirements.

Convert the Datetime into only date, so i tried the below and its failing

select TO_TIMESTAMP((body:message_body:order:order_datetime), ‘yyyy-mm-dd HH24:MI:SS’) 
FROM “stage_table”

. its failing with below error message

SQL compilation error: error line 1 at position 7 too many arguments for function [TO_TIMESTAMP(GET(GET(GET(stage_table.BODY, ‘message_body’), ‘order’), ‘order_datetime’), ‘yyyy-mm-dd HH24:MI:SS’)] expected 1, got 2

I have to subtract the minutes from order_datetime. I have to subtract timezone_offset_minutes from order_datetime

select datetime, dateadd(minute, -300, body:message_body:order:complete_datetime) 
FROM
“stage_table”

. its failing with below error message

Timestamp ‘’ is not recognized

Any quick help is hugely appreciated.

Thanks


回答1:


This will work if you cast the extracted order_datetime to string with ::string:

with sample_table as ( 
select parse_json(replace(replace('{
“message_body”: {
“campus_code”: “TEST”,
“campus_name”: “TEST”,
“event_type”: “TEST”,
“location_code”: “A00000”,
“location_name”: “TEST”,
“order”: {
“credit_total”: 0,
“app_version”: “1.0.9”,
“asap”: 1,
“order_datetime”: “2021-01-08 18:19:34”
}
,
“timezone_offset_minutes”: -360,
}
}', '“', '"'), '”', '"')) body
)

select TO_TIMESTAMP(body:message_body:order:order_datetime::string, 'yyyy-mm-dd HH24:MI:SS')
from sample_table

-- 2021-01-08T18:19:34Z



来源:https://stackoverflow.com/questions/66029727/to-convert-date-in-snowflake

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!