【问题标题】:How to delimit string(s) and convert to column headers?如何分隔字符串并转换为列标题?
【发布时间】:2020-05-01 07:01:13
【问题描述】:

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

例子:

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

【问题讨论】:

  • 您使用的是哪个 dbms?
  • 请注意,表格有,而不是字段。
  • Microsoft SQL Server 标准版 12
  • 最好的方法是修复设计并停止存储分隔字符串。它违反了 1NF,而且很痛苦。鉴于这种动态的性质,如果您坚持使用这种架构,您将需要动态 sql。
  • 分隔字符串不在我的控制范围内,所以它会保持这种状态。希望某种支点方法可以做到,只是不知道如何。

标签: sql sql-server text dynamic csv


【解决方案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 是一个 dbfiddle。

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

【讨论】:

  • 它需要是动态的,因为 column1 中的值是随机的,新列是根据这些值动态创建的。
  • @hooch 您应该仔细考虑这种动态方法。您可能很难使用这样的结果集。随着源代码中可能值的数量增加,代码和结果集变得越笨拙。您在示例数据中使用单个字符值 - 如果您的值有多个字符怎么办?
猜你喜欢
  • 2010-10-19
  • 2022-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多