可变长度,可变分隔符的分割字符串

问题描述 投票:0回答:1

阅读提出的问题here,但是我的问题要复杂一些。

我有一个长度可变的字符串,分隔符有时可以是两个破折号,有时也可以只是一个破折号。假设在我的表格中,我要细分的数据存储在这样的单列中:

+ -----------------------------------------+
| Category                                 |
+------------------------------------------+
| Zoo - Animals - Lions                    |
| Zoo - Personnel                          |
| Zoo - Operating Costs - Power / Cooling  |
+------------------------------------------+

但是我想将数据列从单个列输出到三个独立的列中,如下所示:

+----------+--------------------+-----------------+
| Location | Category           | Sub-Category    |
+----------+--------------------+-----------------+
| Zoo      | Animals            | Lions           |
| Zoo      | Personnel          |                 |
| Zoo      | Operating Costs    | Power / Cooling |
+----------+--------------------+-----------------+

希望获得一些指导,因为我在Google上发现的样本似乎比这更简单。

sql-server tsql substring sql-server-2017
1个回答
0
投票

一点点破解,但是有效:

DECLARE @t TABLE (Category VARCHAR(255));

INSERT @t (Category)
VALUES ('Zoo - Animals - Lions'),('Zoo - Personnel'),('Zoo - Operating Costs - Power / Cooling');

;WITH split_vals AS (
    SELECT Category AS Cat,TRIM(Value) AS Value,ROW_NUMBER() OVER (PARTITION BY Category ORDER BY Category) AS RowNum
    FROM @t
    CROSS APPLY STRING_SPLIT(Category,'-')
), x AS (
    SELECT
        Cat,
        CASE WHEN RowNum = 1 THEN Value END AS Location,
        CASE WHEN RowNum = 2 THEN Value END AS Category,
        CASE WHEN RowNum = 3 THEN Value END AS [Sub-Category]
    FROM split_vals
)
SELECT STRING_AGG(Location,'') AS Location, STRING_AGG(Category,'') AS Category, STRING_AGG([Sub-Category],'') AS [Sub-Category]
FROM x
GROUP BY Cat;
© www.soinside.com 2019 - 2024. All rights reserved.