You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQL中从第二个短横线后拆分字段字符串至多列?

搞定Customer_Group字段拆分:忽略内部连字符,按分隔符拆分

问题根因

你之前的SQL错在拿单个-当拆分标记,直接把IT-BOUSH拆成了IT。实际咱们要拆分的是字段里用来分隔公司、城市、国家的**-(空格+短横线+空格)**,得把公司名称自带的连字符完全忽略。

正确的UPDATE语句

UPDATE my_table
SET 
    -- 取第一个` - `前面的内容当公司名
    Company = TRIM(SUBSTR(Customer_Group, 1, INSTR(Customer_Group, ' - ') - 1)),
    -- 取第一个和第二个` - `之间的内容当城市名
    City = TRIM(SUBSTR(
        Customer_Group, 
        INSTR(Customer_Group, ' - ') + 3,  -- 跳过第一个` - `(占3个字符)
        INSTR(Customer_Group, ' - ', INSTR(Customer_Group, ' - ') + 1) - (INSTR(Customer_Group, ' - ') + 3)
    )),
    -- 取第二个` - `后面的内容当国家名
    Country = TRIM(SUBSTR(
        Customer_Group, 
        INSTR(Customer_Group, ' - ', INSTR(Customer_Group, ' - ') + 1) + 3
    ))

语句说明

  1. Company字段:用INSTR定位第一个-的位置,截取该位置之前的内容,再用TRIM清除首尾空格,就能完整拿到IT-BOUSH这类带内部连字符的公司名称。
  2. City字段:先找到第一个-的位置并向后偏移3位(跳过分隔符本身),再定位第二个-的位置,计算两个位置的差值得到截取长度,最终得到城市名。
  3. Country字段:找到第二个-的位置并向后偏移3位,截取剩余内容后清除空格,得到国家名称。

兼容不规范分隔符

如果部分记录里的分隔符是- (短横线+空格,比如示例中的Swindon- United Kingdom),可以先统一替换分隔符格式再拆分,避免出错:

UPDATE my_table
SET 
    Company = TRIM(SUBSTR(REPLACE(Customer_Group, '- ', ' - '), 1, INSTR(REPLACE(Customer_Group, '- ', ' - '), ' - ') - 1)),
    City = TRIM(SUBSTR(
        REPLACE(Customer_Group, '- ', ' - '), 
        INSTR(REPLACE(Customer_Group, '- ', ' - '), ' - ') + 3,
        INSTR(REPLACE(Customer_Group, '- ', ' - '), ' - ', INSTR(REPLACE(Customer_Group, '- ', ' - '), ' - ') + 1) - (INSTR(REPLACE(Customer_Group, '- ', ' - '), ' - ') + 3)
    )),
    Country = TRIM(SUBSTR(
        REPLACE(Customer_Group, '- ', ' - '), 
        INSTR(REPLACE(Customer_Group, '- ', ' - '), ' - ', INSTR(REPLACE(Customer_Group, '- ', ' - '), ' - ') + 1) + 3
    ))

这段代码先把所有- 格式的分隔符替换成统一的-,再按之前的逻辑拆分,适配不同格式的原始数据。

内容的提问来源于stack exchange,提问作者R Sem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 05:25:23