sql - SQL 将 2 个字段拆分为行
问题描述
我有一行看起来像这样的数据:
200,500,1000 | 50,100,200 | TUA03 | 2019-02-21
从以下查询。
select distinct
tbl.qualifier_value,
tbl.h_discount_val,
tbl.longlist_mm_text,
tbl.p_start_date
from @HoldingTable tbl
我需要将前两个字段拆分为新的相应行。给出以下输出。
200 | 50 | TUA03 | 2019-02-21
500 | 100 | TUA03 | 2019-02-21
1000 | 200 | TUA03 | 2019-02-21
我可以像这样得到第一个字段拆分:
select distinct
s.Item,
tbl.h_discount_val,
tbl.longlist_mm_text,
tbl.p_start_date
from @HoldingTable tbl
outer apply [dbo].[Split](qualifier_value, ',') s
这使:
1000 | 50,100,200 | TUA03 | 2019-02-21
200 | 50,100,200 | TUA03 | 2019-02-21
500 | 50,100,200 | TUA03 | 2019-02-21
我现在还需要拆分第二个字段,但要小心地将位置绑定到第一列的正确位置。通过外部对第二个字段应用相同的想法,我得到了 9 行,但我无法匹配从第一个字段值位置匹配的第二个字段值。
这是可以实现的吗?
解决方案
一种方法是递归CTE。我有点不清楚列名是什么,所以我把它们设为通用:
with cte as (
select left(col1, charindex(',', col1) - 1) as col1,
left(col2, charindex(',', col2) - 1) as col2,
col3, col4,
stuff(col1, 1, charindex(',', col1), '') as col1_rest,
stuff(col2, 1, charindex(',', col2), '') as col2_rest
from t
union all
select left(col1_rest, charindex(',', col1_rest + ',') - 1) as col1,
left(col2_rest, charindex(',', col2_rest + ',') - 1) as col2,
col3, col4,
stuff(col1_rest, 1, charindex(',', col1_rest + ','), '') as col1_rest,
stuff(col2_rest, 1, charindex(',', col2_rest + ','), '') as col2_rest
from cte
where col1_rest > ''
)
select col1, col2, col3, col4
from cte;
这是一个 db<>fiddle。
推荐阅读
- python - TypeError: __init__() 得到了一个意外的关键字参数“log_dir”
- string - golang 在编译时删除 const 字符串中的字符(用于提高可读性)(空格、\n 和 \t)
- flutter - 想要建议使用 dart 在颤振中创建 UI
- r - r中的文本分析
- python - 如何打开 android sdk 24 管理器
- ironpython - 如何使用 IronPython 向 Spotfire 上的图形表上的图标添加操作
- django - 准备一个命令的字符串表示,然后执行 id
- c# - 如何将子实体映射到 EF Core 中的同一个表
- java - 使用枚举变量切换字符串
- r - 将数据框中的某个范围内的值乘以一个数字