【问题标题】:SQL Substring to fetch values which inside Bracket only i.e. ()SQL 子字符串仅获取括号内的值,即 ()
【发布时间】:2021-03-18 10:26:07
【问题描述】:

对于您的专家来说可能很容易,但我在这里发现了一个挑战- 我的列数据如下所示,我需要将括号()内的值分开。我的字符串模式永远是这样的。

J Zeneta (A50103050); S Rao (B499487)

输出应该是

Col1        Col2
A50103050   B499487

【问题讨论】:

  • 您使用的是什么 DBMS?您是说“J Zeneta (A50103050); S Rao (B499487)”是单行单列中的单个字符串/varchar 值吗?

标签: sql sql-server substring


【解决方案1】:

你可以试试这个,它可能需要根据你的 RDBMS 进行调整,这是针对 SQLServer 的

select Left(value, CharIndex(')',value)-1) from (
    select value from String_Split('J Zeneta (A50103050); S Rao (B499487)','(')
    where value like '%)%'
)x

编辑

有一个简单的case 可以产生列,就像这样

select max(case when rn=1 then Value end) Col1, max(case when rn=2 then value end) Col2 from ( 
    select Left(value, CharIndex(')',value)-1) [Value], Row_Number() over (order by (select null)) rn from (
            select value from String_Split('J Zeneta (A50103050); S Rao (B499487)','(')
            where value like '%)%'
    )x
)x

编辑 2

使用现有表示例中的数据

create table #Test (id int, col varchar(50))
insert into #Test select 1, 'J Zeneta (A50103050); S Rao (B499487)' 
insert into #Test select 2, 'Bob Builder (12345); Mr Rambo (67890)'

select id, max(case when (rn % 2)=0 then Value end) Col1, max(case when (rn % 2)!=0 then value end) Col2 from ( 
    select id, Left(value, CharIndex(')',value)-1) [Value], Row_Number() over (order by (select null)) rn from (
            select id, value
            from #Test t cross apply String_Split(t.col,'(')
            where value like '%)%'
    )x
)x
group by id

【讨论】:

  • 感谢@Stu,这非常接近,但是输出应该显示为列而不是行。请提出建议。
  • 您的问题中的输出有行吗?
  • 抱歉,我认为它是自动显示为有问题的行,因此我提到了 Col1 Col2。
  • 好吧,这不难做到,上面已经更新了:)
  • 再次道歉,但是我应该把 Table.Column 引用作为我给出的字符串,但是它是 Table 中的一些 Column 以将查询作为 TSQL 运行
猜你喜欢
  • 2016-05-04
  • 1970-01-01
  • 2012-06-30
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 2012-01-24
  • 1970-01-01
相关资源
最近更新 更多