阅读提出的问题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上发现的样本似乎比这更简单。
一点点破解,但是有效:
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;