sql - 如何分隔字符串并转换为列标题?
问题描述
如何获取字符串并转换为列(随着源字符串的变化而动态变化):
例子:
(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|
解决方案
使用like
和case
:
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。
我会让你构建查询的其余部分。
推荐阅读
- javascript - @input 在相同组件角度问题的不同实例中
- kubernetes - 使用 terraform 动态连接到 GKE 集群
- javascript - firebase 创建用户承诺
- python - 使用Biopython从python中的.fasta基因中提取基因起始位置
- javascript - 无法找到按钮以查找其禁用状态以进行测试
- python - 文本未知原因的 Tkinter 消息换行
- ios - 在 SWIFT 5 中点击时无法更改 UIImage systemName 图像
- sql-server - VBA使用'编写SQL字符串而没有被注释掉?
- javascript - 在拦截器中手动设置 auth 'Cookie' 是否安全?
- arrays - 在二维数组中查找整数行