问题
我不能 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:现场历史
表2:我想加入的事情
表 3:我梦想的最终表
我尝试过的内容
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/