如何分隔字符串并转换为列标题?

问题描述 投票:3回答:1

如何获取字符串并将其转换为列(动态更改源字符串):

示例:

(select *
 from table 
 inner join
    (select column1, [dynamic field] from table) as dynamic_data
 on table.column1 = dynamic_data.column1)


Column1
------
a,b,c
c,d,e
a,f,e

对此

column1 a b c d e f
-------------------
a,b,c  |x|x|x| | | |
c,d,e  | | |x|x|x| |
a,f,e  |x| | | |x|x|
sql sql-server text dynamic delimited-text
1个回答
1
投票

使用likecase

select column1,
       (case when ',' + column1 + ',' like '%,a,%' then 'x' end) as a,
       (case when ',' + column1 + ',' like '%,b,%' then 'x' end) as b,
       (case when ',' + column1 + ',' like '%,c,%' then 'x' end) as c,
       (case when ',' + column1 + ',' like '%,d,%' then 'x' end) as d,
       (case when ',' + column1 + ',' like '%,e,%' then 'x' end) as e,
       (case when ',' + column1 + ',' like '%,f,%' then 'x' end) as f
from t;

我不确定为什么需要“动态”。问题不是源字符串,而是目标列。如果需要与源字符串匹配的字符串,则需要使用动态SQL。 。 。这似乎相当复杂。

编辑:

动态SQL的核心是将case表达式放在一起。您可以使用string_split()string_agg()(或旧版本的SQL Server中的等效功能)来执行此操作:

select string_agg(replace('      (case when '','' + column1 + '','' like ''%,[value],%'' then ''x'' end) as [value]', '[value]', value), '
'
                 ) within group (order by value) as cols
from (select distinct value
      from t cross apply
           string_split(t.column1, ',')
     ) t

Here是db <>小提琴。

我将让您构造其余的查询。

© www.soinside.com 2019 - 2024. All rights reserved.