繁体   English   中英

如何从 SQL 中的子字符串中间提取值?

[英]How to extract value from middle of substring in SQL?

我有一个名为“CustomerId”的列,其值为“1_Nissan_028”和“2_Ferrari_035”。

我想将“Nissan”或“Ferrari”提取为“CustomerName”。 CustomerName 位于 CustomerId 的中间,长度不同。

以下 SQL 查询返回值,例如“Nissan_”或“Ferrar”。

如何编写SQL语句?

SELECT cast(
        SUBSTRING(
        CustomerId,
        6,
        charindex('_', CustomerId)
        ) as nvarchar(32)
    ) as CustomerName
  
FROM [sales].[CustomerSales] 

假设该值始终是第二个分隔值,您可以使用STRING_SPLIT及其ordinal列来实现此目的:

SELECT SS.value AS CustomerName
FROM sales.CustomerSales CS
     CROSS APPLY STRING_SPLIT(CS.CustomerId,'_',1) SS
WHERE SS.ordinal = 2;

另一种古怪的做法是使用翻译

with customersales as (
  select '1_Nissan_028' CustomerId union select '2_Ferrari_035'
)
select customerId,
  Replace(Translate(customerId, '0123456789','__________'),'_','') CustomerName
from customersales;

暂无
暂无

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

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