sql - 无法在 Snowflake 中具有混合数据类型的字段上内部连接两个简单的 CTE

标签 sql snowflake-cloud-data-platform common-table-expression

问题

我不能 inner join Snowflake 中的两个简单 CTE。简洁的错误消息没有指明方向。 我的查询出了什么问题?
加分:为什么我的查询可以在 SQL Server 中运行,但不能在 Snowflake 中运行?

背景

我是雪花新手。我习惯了 SQL Server。我要查询inner join雪花中的 2 个表。表 1 和表 2 显示了我想要加入的表。表3就是我想要的结果。

我想使用简单的 where 在 CTE 中删除第一个表中的一些行。条款。当我运行查询时(见下文),我收到一条简洁的错误消息:

Numeric value 'HAHA! IM CAUSING TROUBLE' is not recognized

但我认为我用第一个 CTE“删除”了这个值。

我的查询出了什么问题?加分:为什么我的查询在 SQL Server 中有效,但在 Snowflake 中无效?

表 1:现场历史

<表类=“s-表”> <标题> id 日期 field_id 字段值 <正文> 1 2020-01-01 不需要 哈哈! IM 造成麻烦 2 2020-01-02 东西 100 3 2020-01-03 东西 101 4 2020-01-04 东西 102 5 2020-01-05 东西 空 6 2020-01-06 东西 103

表2:我想加入的事情

<表类=“s-表”> <标题> thing_id thing_start_date thing_end_date something_i_care_about <正文> 100 2020-01-01 2020-02-01 secret 的外星情报 101 2020-02-01 2020-03-01 鲨鱼激光器的蓝图 102 2020-03-01 2020-04-01 非 YA biz-NAZZ 103 2020-04-01 2020-05-01 谁将赢得单例女郎

表 3:我梦想的最终表

<表类=“s-表”> <标题> id 日期 thing_id thing_start_date thing_end_date something_i_care_about <正文> 2 2020-01-02 100 2020-01-01 2020-02-01 secret 的外星情报 3 2020-01-03 101 2020-02-01 2020-03-01 时间机器的蓝图 4 2020-01-04 102 2020-03-01 2020-04-01 非 YA biz-NAZZ 6 2020-01-06 103 2020-04-01 2020-05-01 谁将赢得单例女郎

我尝试过的内容

with field_history as ( -- CTE with simple where clause

  select
      id
      , date
      , to_number(field_value, 38, 0) as thing_id  -- SQL Server equivalent would be cast() or convert()
  from db.schema.history
  where field_id = 'thing' and field_value is not null

),

things_i_want as (

  select
    *
  from db.schema.things

),

final as (
  
  select
    field_history.id
    , field_history.date
    , things.*
  from field_history
  inner join things_i_want on field_history.thing_id = things_i_want.thing_id

)

select * from final

super 有用的错误消息阻止我实现我的梦想

Numeric value 'HAHA! IM CAUSING TROUBLE' is not recognized

最佳答案

Numeric value 'HAHA! IM CAUSING TROUBLE' is not recognized

您的错误消息是类型转换问题,可能出现在此处:

to_number(field_value, 38, 0) as thing_id

您可能认为 where 子句过滤掉了错误值。然而,SQL 引擎可以并且确实重新安排操作。我建议使用 case 表达式来处理这个问题:

(case when field_value regexp '^[0-9]+$'
      then to_number(field_value, 38, 0)
 end) as thing_id

保证 case 表达式按顺序运行表达式。

上述想法(但不适用于 regexp 部分)适用于 SQL Server 和 Snowflake。

仅在 Snowflake 中,您可以使用 try_ 函数:

try_to_number(field_value, 38, 0) as thing_id

关于sql - 无法在 Snowflake 中具有混合数据类型的字段上内部连接两个简单的 CTE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66564942/

相关文章:

postgresql - 带有 PERFORM 数据修改 CTE 查询的 Postgres plpgsql

sql - 使用来自另一个表的随机值更新 SQL 表(无连接条件)

python - Django sql 检查

google-cloud-platform - 读取数据时出错,错误消息 : CSV table references column position 174, 但从位置开始的行:136868 仅包含 94 列

snowflake-cloud-data-platform - 雪花物化 View 不更新

sql - 在 PostgreSQL 的 RECURSIVE WITH 内部使用 WITH

php - PDO 准备语句 - NULL

c# - 外键约束错误但不应该发生

sql - 同一行输出的几种情况

snowflake-cloud-data-platform - 使用 Snowflake 进行参数化查询并从 Snowflake .NET Connector 传递值