Split column data into multiple rows

泄露秘密 提交于 2021-02-07 09:34:49

问题


I have data currently in my table like below under currently section. I need the selected column data which is comma delimited to be converted into the format marked in green (Read and write of a category together)

Any ways to do it in SQL Server?

Please do look at the proposal data carefully.... Maybe I wasn't clear before: this isn't merely the splitting that is the issue but to group all reads and writes of a category together(sometimes they are just merely reads/writes), it's not merely putting comma separated values in multiple rows.

--    script:
    use master 
    Create table prodLines(id int  , prodlines varchar(1000))
    --drop table prodLines
    insert into prodLines values(1, 'Automotive Coatings (Read), Automotive Coatings (Write), Industrial Coatings (Read), S.P.S. (Read), Shared PL''s (Read)')
    insert into prodLines values(2, 'Automotive Coatings (Read), Automotive Coatings (Write), Industrial Coatings (Read), S.P.S. (Read), Shared PL''s (Read)')

    select * from prodLines

回答1:


Using Jeff's DelimitedSplit8K

; 
with cte as
(
    select  id, prodlines, ItemNumber, Item = ltrim(Item),
        grp = dense_rank() over (partition by id order by replace(replace(ltrim(Item), '(Read)', ''), '(Write)', ''))
    from    #prodLines pl
        cross apply dbo.DelimitedSplit8K(prodlines, ',') c
)
select  id, prodlines, prod = stuff(prod, 1, 1, '')
from    cte c
    cross apply
    (
        select  ',' + Item
        from    cte x
        where   x.id    = c.id
        and x.grp   = c.grp
        order by x.Item
        for xml path('')
    ) i (prod)



回答2:


Take a look at STRING_SPLIT, You can do something like:

SELECT user_access
FROM Product
CROSS APPLY STRING_SPLIT(user_access, ',');

or what ever you care about.




回答3:


Simply use LATERAL VIEW EXPLODE function:

select access  from Product
LATERAL VIEW explode(split(user_access, '[,]')) usrAccTable AS access;


来源:https://stackoverflow.com/questions/36565224/split-column-data-into-multiple-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!