首页 > 解决方案 > 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 行,但我无法匹配从第一个字段值位置匹配的第二个字段值。

这是可以实现的吗?

标签: sqlsql-servertsqlsplit

解决方案


一种方法是递归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。


推荐阅读