我希望将多个子字符串堆叠在一列中。我正在寻找 UNION ALL 的替代方案,因为我的真实数据很大,并且每行出现超过 30 次子字符串。
下面的代码为我解析出子字符串,但为每个子字符串创建列。我希望将这些 smp 和 smp_Num 堆叠在一列下。我尝试使用内部联接和取消透视,但它对我不起作用。我正在使用 Oracle Sql Developer。
SELECT Prod_Typ,
SUBSTR(Product, 1, 3) as Smp,
SUBSTR(Product, 4, 4) as Smp_Num,
SUBSTR(Product, 8, 3) as Smp1,
SUBSTR(Product, 11, 4) as Smp_Num1,
SUBSTR(Product, 15, 3) as Smp2,
SUBSTR(Product, 18, 4) as Smp_Num2,
SUBSTR(Product, 22, 3) as Smp3,
SUBSTR(Product, 25, 4) as Smp_Num3,
FROM my_table
我的数据如下所示。
产品_类型 | 产品 |
---|---|
11789 | AAD3241HHA3261UUB MNN4567 |
11790 | TTN7689KJI FSS9980 |
我正在寻找的数据是什么样的:
产品_类型 | Smp | Smp_Num |
---|---|---|
11789 | AAD | 3241 |
11789 | 哈哈 | 3261 |
11789 | UUB | |
11789 | MNN | 4567 |
11790 | TTN | 7689 |
11790 | KJI | |
11790 | FSS | 9980 |
从 Oracle 12 开始,您可以使用:
SELECT Prod_Typ,
SUBSTR(product, n * 7 - 6, 3) AS smp,
SUBSTR(product, n * 7 - 3, 4) AS Smp_Num
FROM my_table
CROSS JOIN LATERAL (
SELECT LEVEL AS n
FROM DUAL
CONNECT BY LEVEL <= LENGTH(product)/7
)
对于样本数据:
CREATE TABLE my_table(Prod_Typ, Product) AS
SELECT 11789, 'AAD3241HHA3261UUB MNN4567' FROM DUAL UNION ALL
SELECT 11790, 'TTN7689KJI FSS9980' FROM DUAL
输出:
产品类型 | SMP | SMP_NUM |
---|---|---|
11789 | AAD | 3241 |
11789 | 哈哈 | 3261 |
11789 | UUB | |
11789 | MNN | 4567 |
11790 | TTN | 7689 |
11790 | KJI | |
11790 | FSS | 9980 |