简体   繁体   English

使用SQL从字符串中提取字符

[英]Extract characters from string using SQL

I have a column of ID's and I am needing to use SQL to extract the first two characters after the " - " 我有一列ID,我需要使用SQL提取“-”后的前两个字符

I am using the Custom SQL Query in Tableau 10.4 我在Tableau 10.4中使用自定义SQL查询

Example Column: 示例列:

ABC - BCA - IT
AD - HD - A
QWE - QWE - E

What I need: 我需要的:

BC
HD
QW

I have tried to use the substring and Charindex function, but cannot seem to get it. 我试图使用子字符串和Charindex函数,但似乎无法获取它。 Any ideas? 有任何想法吗?

You can use: 您可以使用:

select substring(example, charindex(' - ', example) + 3, 2)
from (values ('ABC - BCA - IT'), ('AD - HD - A')) v(example)

如果使用的是SQL Server,则可以使用substring()函数:

select substring(col, charindex('-', col) + 1, 2)) as need

With MySQL , there are a lot of possible expressions. 使用MySQL ,有很多可能的表达式。 The big difference is handling of string values that don't contain exactly two dash characters. 最大的不同是处理不完全包含两个破折号的字符串值。

MySQL provides a handy SUBSTRING_INDEX function. MySQL提供了一个方便的SUBSTRING_INDEX函数。

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring-index https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring-index

Assuming the string values contain exactly two dash characters, then something like this: 假设字符串值正好包含两个破折号,则如下所示:

 SELECT c.foo
      , TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(c.foo,'-',2),'-',-1)) AS mid
   FROM ( 
          SELECT  'ABC - BCA - IT' AS foo
          UNION ALL SELECT 'AD - HD - A'
          UNION ALL SELECT 'QWE - QWE - E'
        ) c

Omit the TRIM function if we don't want to remove the leading and trailing spaces. 如果我们不想删除前导和尾随空格,请省略TRIM函数。

foo              mid
---------------  ---
ABC - BCA - IT   BCA
AD - HD - A      HD
QWE - QWE - E    QWE

It's been a while since I've worked with Tableau, but IIRC this would be something this should work: 自从我与Tableau合作以来已经有一段时间了,但是IIRC应该会起作用:

LEFT(TRIM(SPLIT([Column], `-`, 2)), 2)

To the best of my knowledge, no version of Tableau supports substring . 就我所知,Tableau的任何版本都不支持substring

Alternatively, this might also help: 或者,这也可能有帮助:

MID([Column], FIND([Column], "-") + 2, 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM