基于列值的重复行

时间:2017-11-24 15:00:47

标签: sql tsql reporting-services ssrs-2008 ssrs-2012

在一列中有多个值时,我需要复制行。 例如:

A  B  12  I76J-I76H=>
A  B  12  I76J
A  B  12  I76H

谢谢。

1 个答案:

答案 0 :(得分:0)

由于用户@RichardTheKiwi提供大部分代码HERE

,因此信用额度很高

无论如何这里是代码。如果你想更改sql,以便它不会基于 - 只是替换所有 - 与你选择的字符分开。

创建表格:

    create table Testdata(Data1 varchar(50), Data2 varchar(50), Data3 int, Data4 varchar(max))
    insert Testdata select 'A', 'E', '9', 'I76J-I76H-I76I-I76G'
    insert Testdata select 'B', 'F', '8', 'I76J-I76H-I76I'
    insert Testdata select 'C', 'G', '7', 'I76J-I76H'
    insert Testdata select 'D', 'H', '6', 'I76J'

现在更新原始表TestData

;with tmp(Data1, Data2, Data3, DataItem, Data4) as (
select Data1, Data2, Data3, LEFT(Data4, CHARINDEX('-',Data4+'-')-1),
    STUFF(Data4, 1, CHARINDEX('-',Data4+'-'), '')
from Testdata
union all
select Data1, Data2, Data3, LEFT(Data4, CHARINDEX('-',Data4+'-')-1),
    STUFF(Data4, 1, CHARINDEX('-',Data4+'-'), '')
from tmp
where Data4 > ''
)
INSERT INTO Testdata
select Data1, Data2, Data3, DataItem AS Data4
from tmp
order by Data1

DELETE FROM Testdata
where Data4 like '%-%'

select * FROM TESTDATA