【问题标题】:Convert string to date and use in a Where statement将字符串转换为日期并在 Where 语句中使用
【发布时间】:2020-08-21 23:18:44
【问题描述】:

我正在使用 Snowflake 门户,需要在 where 语句中使用 sold_dt 字段作为条件。但是 sold_dt 以 (yyyymmdd) 格式存储为 varchar。我试过转换没有成功。我收到此错误 - SQL compilation error: error line 2 at position 8 invalid identifier 'DATETIME'

select
  convert(datetime, a.sold_dt) as sold_date,
  count(a.vin)
from MyTable a
where sold_date >= '2020/04/01'
group by 1
limit 100

【问题讨论】:

  • 试试to_date(a.sold_dt,'YYYYMMDD')
  • select to_date('20200501','yyyymmdd'); 工作

标签: sql date type-conversion snowflake-cloud-data-platform


【解决方案1】:

所以看来您的日期格式设置可能与我的不同,因为我需要将 WHERE 子句更改为 'yyyy-mm-dd' 格式,但这表明它有效:

WITH example_data AS (
    select * from values ('20200501', 'VIN_A'), ('20200501', 'VIN_B') v(sold_dt, vin)
)
select
  to_date(a.sold_dt,'YYYYMMDD') as sold_date,
  count(a.vin)
from example_data a
where sold_date >= '2020-04-01'
group by 1
limit 100;

给予:

SOLD_DATE   COUNT(A.VIN)
2020-05-01  2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多