【问题标题】:How to get 2 sub strings as 2 columns from single column of table如何从表的单列中获取 2 个子字符串作为 2 列
【发布时间】:2017-09-19 09:32:12
【问题描述】:

[{"key":"Mobile","value":"9100617634"},{"key":"Email","value":"balajirao1@ziaff.in"}]

上面的一个代表一个表的一列中的值。 我想要 2 个名为 mobile 和 email 的列,它们的值分别为 9000617634,balajirao@ziraff。 如何进入sql server。

见下图。

mobile             Email
------             ------------
9100617634         balajirao1@ziaff.in

【问题讨论】:

标签: sql-server msbi


【解决方案1】:

你可以使用 Pivot 函数将行值转换为列, 下面是实现的静态代码

SELECT * FROM(
   SELECT
     columns_name
   FROM
      table_name
     ) M
   PIVOT (MAX(Key) FOR table_name IN (mobile ,Email))AS  P ;

【讨论】:

    【解决方案2】:

    嗯,辛苦地做这件事很有趣:)

    --initial string
    declare @s1 varchar(1000) = (select '[{"key":"Mobile","value":"9100617634"},{"key":"Email","value":"balajirao1@ziaff.in"}]')
    
    --selecting first part and second part of string
    declare @mobile varchar(100) = (select right(left(@s1,charindex('}',@s1)-1),len(left(@s1,charindex('}',@s1))) - charindex(':',left(@s1,charindex('}',@s1)))-1))
    declare @mail varchar(100) = (select right(@s1,charindex(':',reverse(@s1))-1))
    
    --getting rid of extra characters
    set @mobile = (right(@mobile, len(@mobile) - charindex(':',@mobile)))
    set @mail = (left(@mail, len(@mail) - charindex('}',reverse(@mail))))
    
    
    --getting rid of double quotes
    set @mobile = replace(@mobile,'"','')
    set @mail = replace(@mail,'"','')
    
    --selecting data
    select 
    @mobile as Mobile,
    @mail as Mail
    

    结果如下:

    手机邮件

    9100617634 balajirao1@ziaff.in

    【讨论】:

      【解决方案3】:

      选择 当 [MOBILE/PHONE] 像 '[a-z]%' 然后为 null 否则 [MOBILE/PHONE] 以 [MOBILE/PHONE] 结尾时, ISNUMERIC(email)=0 然后 EMAIL 以 EMAIL 结尾的情况 从 ( 选择 REPLACE(SUBSTRING(RIGHT(right(left(AC.Communication,charindex('}',AC.Communication)),len(left(AC.Communication,charindex('}',AC.Communication))) - charindex(' :',left(AC.Communication,charindex('}',AC.Communication)))),LEN(right(left(AC.Communication,charindex('}',AC.Communication)),len(left(AC .Communication,charindex('}',AC.Communication))) - charindex(':',left(AC.Communication,charindex('}',AC.Communication)))))-CHARINDEX(':',right (left(AC.Communication,charindex('}',AC.Communication)),len(left(AC.Communication,charindex('}',AC.Communication))) - charindex(':',left(AC.Communication) Communication,charindex('}',AC.Communication)))))),2,CHARINDEX(']',AC.Communication)),'"}','') AS [手机/电话], 替换(替换(左(右(AC.Communication,charindex(':',reverse(AC.Communication))),LEN(右(AC.Communication,charindex(':',reverse(AC.Communication))))) -charindex('}',reverse(right(AC.Communication,charindex(':',reverse(AC.Communication)))))),':"',''),'"','') AS电子邮件

      来自 DimAccountContact 作为 AC

      【讨论】:

      • 根据对上述答案所做的一些更改为我获得了所需的结果
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 2016-03-05
      • 2012-01-12
      相关资源
      最近更新 更多