【发布时间】:2020-04-24 11:12:35
【问题描述】:
我有以下数据集。我正在尝试将 Col =“Str_B_Class”中的字符串与 col =“Str_A”中的整个字符串匹配。 str_A col 将数据作为类:值。如果在 Str_A 中找到该类,则 sql 应将冒号后的值放入 desired_output_column ,否则为 0
下面代码的问题是,如果它让我们说找到 3132,并且值 10,那么如果返回 1 行匹配 3132,它会返回 6 次。所以它正在爆炸整个数据集。我需要一些帮助来匹配字符串而不导致整个表爆炸。
Customer_ID || Str_A || Str_B_Class || Desired_Output
-------------------------------------------------------------------------------------------
A1 || 121:8|188:8|3123:10|3125:10|3131:10|3132:10 || 3132 || 10
A1 || 121:8|188:8|3123:10|3125:10|3131:10|3132:10 || 3125 || 10
A1 || 121:8|188:8|3123:10|3125:10|3131:10|3132:10 || 4141 || 0
查询:
select
s.Customer_Id,
s.Str_A,
s.Str_B_Class,
case when s.instance_id = s.Str_B_Class
then s.Count_of_instances
else '0'
end AS Desired_Output
from (
select
Customer_Id, Str_A,
Str_B_Class,
explode(str_to_map(Str_A,'[|]','[:]')) as (instance_id, Count_of_instances)
from my_table
) as s
【问题讨论】:
-
在您的示例数据中,标题 (3) 中的列数与数据行中的列数不匹配。因此很难理解你的意思。
-
请标记您的数据库
-
在使用 case 语句检查字符串是否匹配后,我正在添加一个新列“Desired_Output”。
-
另外,我在内部查询中所做的是爆炸数据以查找“:”之后的值。有一个更好的方法吗?该数据集跨越约 3M 行,我不确定爆炸将如何影响性能
-
@Samy:你真的应该考虑修复你的数据模型:而不是将 CSV 列表存储在数据库列中,你应该有一个单独的表,每个 CSV 元素都有一行,以及一个引用父表。这里是a recommended reading for the motivations。
标签: sql apache-spark hive