gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:40:40 24 4
gpt4 key购买 nike

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

例子:

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

最佳答案

使用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是一个数据库<> fiddle 。

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

关于sql - 如何分隔字符串并转换为列标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59735699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com