gpt4 book ai didi

mysql - 选择字符串直到字符串中的第一个或第二个空格

转载 作者:行者123 更新时间:2023-11-29 05:24:48 25 4
gpt4 key购买 nike

我有一个表格列,每一行都包含这样的数据:

|                 Simbols              |
|--------------------------------------|
|H412 Text text |
|H413 Text text text text |
|EUH 001 Text text text text text text |
|EUH 006 text text |
|EUH 201/201A Text text. Text text |

我需要从该数据中获取如下数据:

|Simbols     |
|------------|
|H412 |
|H413 |
|EUH 001 |
|EUH 006 |
|EUH 201/201A|

我尝试使用 SUBSTRING 和 CHARINDEX 但它直到最后都不起作用......它只需要第一个空格或类似的东西......查询:

SELECT 
CASE
WHEN SUBSTRING(Simbols, 1, CHARINDEX(' ', Simbols)) = ''
THEN Simbols + ' '
ELSE SUBSTRING(Simbols, 1, CHARINDEX(' ', Simbols))
END 'Simbols'
FROM dbo.table

结果:

|  Simbols   |
|------------|
|H412 |
|H413 |
|EUH |
|EUH |
|EUH |

我怎样才能做到这一点,问题出在哪里?也许有不同的方法来获得这些 Simbols?
附言以“文字文字文字”为例,附有“Simbols”的解释

最佳答案

The CharIndex() function有一个可选的第三个参数 - start_location - 这将是这里的关键。

SELECT your_column
, CharIndex(' ', your_column) As first_space
, CharIndex(' ', your_column, CharIndex(' ', your_column) + 1) As second_space
, SubString(your_column, 1, CharIndex(' ', your_column, CharIndex(' ', your_column) + 1)) As first_two_words
FROM your_table

不幸的是,当 CharIndex() 函数找不到指定的字符串(在本例中为单个空格 ' ')时,它将返回 0(零)。

这意味着如果没有第一个或第二个空格,我上面示例中的 first_two_words 的结果将返回一个空字符串,如 SubString(your_column, 1, 0) = ' '.

要解决这个问题,您需要有点聪明。

本质上,如果 second_space = 0 那么我们需要返回完整的字符串。为此,我们有几个选择:

SELECT your_column
, CharIndex(' ', your_column) As first_space
, CharIndex(' ', your_column, CharIndex(' ', your_column) + 1) As second_space
, SubString(your_column, 1, CharIndex(' ', your_column, CharIndex(' ', your_column) + 1)) As first_two_words
, SubString(your_column, 1, Coalesce(NullIf(CharIndex(' ', your_column, CharIndex(' ', your_column) + 1), 0), Len(your_column))) As first_two_words_option1
, CASE WHEN CharIndex(' ', your_column, CharIndex(' ', your_column) + 1) = 0 THEN your_column ELSE SubString(your_column, 1, CharIndex(' ', your_column, CharIndex(' ', your_column) + 1)) END As first_two_words_option2
FROM (
SELECT 'one' As your_column
UNION ALL SELECT 'one two'
UNION ALL SELECT 'one two three'
UNION ALL SELECT 'one two three four'
) As x

关于mysql - 选择字符串直到字符串中的第一个或第二个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21456821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com