SQL将2个字段拆分为行
我有一行数据如下所示:SQL将2个字段拆分为行,sql,sql-server,tsql,split,Sql,Sql Server,Tsql,Split,我有一行数据如下所示: 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 |
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;
一种方法是递归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;
是一个数据库编辑器。这太神奇了,我想我还没有在SQL查询中看到递归。你知道类似的解决方案在更大的数据集上的性能如何吗?戈登,我已经实现了你的解决方案,它正在工作,非常感谢。@Zero。对于这类问题(每行仅使用行内的操作执行少量递归步骤),即使在大型表上,递归也应该相当合理。还有其他一些情况下,大小会影响性能。这是令人惊讶的,我认为我没有在SQL查询中看到递归。你知道类似的解决方案在更大的数据集上的性能如何吗?戈登,我已经实现了你的解决方案,它正在工作,非常感谢。@Zero。对于这类问题(每行仅使用行内的操作执行少量递归步骤),即使在大型表上,递归也应该相当合理。在其他情况下,尺寸会影响性能。