sql - 在 SQL (Redshift) 中提取字符串并将列转换为行
问题描述
我在一个名为“食物”的表中有一个名为“描述”的列,其中包括多个用 分隔的食物名称,例如鸡肉、汤、面包、可乐
如何从列中提取每个项目并创建多行。例如,目前就像
{FoodID, FoodName, Description}
==> {123, Meal, " chicken, soup, bread, coke "}
我需要的是
{FoodID, FoodName, Description}
==> {123,膳食,鸡肉},{123,膳食,汤},{123,膳食,面包}等。
在 Redshift 中,我首先将“描述”列拆分为
select FoodID, FoodName, Description,
SPLIT_PART(Description, ',',1) AS Item1,
SPLIT_PART(Description, ',',1) AS Item2,
SPLIT_PART(Description, ',',1) AS Item3,.....till Item10
FROM Food
考虑到最多可以有 10 个项目,因此 Item10。将这些列 Item1 转换为 Item10 以存储为行的最佳方法是什么?我尝试了 UNION ALL,但考虑到大量数据需要更长的时间。
解决方案
您的问题在这里得到了专门针对 Redshift 的详细回答。您只需要将您的查询映射到那里提供的示例查询。您的查询将如下所示。
select (row_number() over (order by true))::int as n into numbers from food limit 100;
这将创建数字表。
您的查询将变为:
select foodId, foodName, split_part(Description,',',n) as descriptions from food cross join numbers where split_part(Description,',',n) is not null and split_part(Description,',',n) != '';
现在,回到你最初关于性能的问题。
考虑到大量数据,这需要更长的时间。
考虑到 和 的典型数据仓库用例high read
,seldom write
您应该保留stagging
表中提到的典型食品数据,例如stg_food
。
您应该使用以下类型的查询来一次性插入实际food
表,如下所示。
insert into food select foodId, foodName, split_part(Description,',',n) as descriptions from stg_food cross join numbers where split_part(Description,',',n) is not null and split_part(Description,',',n) != '';
这将写入一次并使您的选择查询更快。
推荐阅读
- python - 我是 Python 的初学者,只是想知道将变量放在函数之前和函数内部之间有什么区别?
- c++ - 构造函数的重新定义
- python - Keras 准确度指标与 CNN 车道检测的自定义指标相比如何?
- apache-kafka - Spark Structured Streaming无法在kafka中writeStream
- python - pytorch:Windows 10 上的 ModuleNotFoundError 异常
- java - 如何暂时阻止单击菜单项的能力
- python - 为什么调用函数和编写语句在 Python 中显式地工作不同?
- python - Python从.txt文件中提取所有href
- rust - 移动后参考与参考前不同
- python - 为什么会出现“IndexError:字符串索引超出范围”?