首页 > 解决方案 > 如何分隔字符串并转换为列标题?

问题描述

如何获取字符串并转换为列(随着源字符串的变化而动态变化):

例子:

(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|

标签: sqlsql-servertextdynamiccsv

解决方案


使用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()and 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

是一个 db<>fiddle。

我会让你构建查询的其余部分。


推荐阅读