在 Spark sql 中使用 JDBC 数据源,我们尝试运行以下查询
select nvl( columnName , 1.0) from tablename
给出错误为
cannot resolve 'nvl(tablename.`columnname`, 1.0BD)' due to data type mismatch: input to function coalesce should all be the same type, but it's [decimal(38,10), decimal(2,1)]
我知道我们可以解决这个问题
select nvl( columnname , CAST( 1.0 as decimal(38,10))) from tablename
看起来我需要找到每一列的数据类型并转换为它。
- 还有其他方法可以处理吗?
- 我可以在加载 csv 格式等数据帧时预先给出架构定义吗? [https://issues.apache.org/jira/browse/SPARK-16848]
- 如何转换每列加载的 Dataframe 数据类型。
最佳答案
- 您可以在 NVL 上使用 Coalesce。合并的输入被转换为“最佳”通用数据类型。
- JDBC 连接使用数据库架构作为其架构,因此不可能预先提供架构。
您可以通过添加另一个
select
将所有列转换为不同的数据类型,这在数据帧/数据集 API 中很容易实现:// Create some toy data. val df = spark.range(100).select($"id", (rand(2) * 10).as("a")) df.printSchema // Define the casts. val casts = Seq(col("id").cast("int"), col("a").cast("int")) // Apply the casts. df.select(casts: _*).printSchema
关于apache-spark - Spark - nvl 函数数据类型不匹配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41138905/