简体   繁体   中英

Splitting columns and retaining different data sets SQL Server

I have a column that I want to split into two and retain only the number within the column.

JU_COUNT1 it contains data like this

JU_COUNT1
1 BOLT 4 ATTACH
2 BOLT 2 ATTACH
3 BOLT 1 ATTACH
0 BOLT 3 ATTACH
2 BOLT 10 ATTACH
2 BOLT 12 ATTACH

After the query runs I want it to look like this

BOLT    ATTACH
1         4 
2         2 
3         1 
0         3 
2        10 
2        12 

My SQL query looks like

SELECT JU_COUNT1,         
CASE
WHEN JU_COUNT1 LIKE '%ATTACH%' THEN RIGHT(JU_COUNT1, Charindex(' ', JU_COUNT1) - 1)
ELSE JU_COUNT1
END AS 'ATTACH1',
CASE
WHEN JU_COUNT1 LIKE '%BOLT%' THEN LEFT(JU_COUNT1, Charindex(' ', JU_COUNT1) - 1)
END AS 'BOLT1'
FROM [dbo].[SUPPORTSTRUCTURE]

I'm able to easily retain the BOLT because its the first part in the data when BOLT is present however retrieving the value for attach is alluding me.

One trick you can try here would be to remove the BOLT and ATTACH text, and then substring out the data you want:

WITH cte AS (
    SELECT
        REPLACE(REPLACE(JU_COUNT1, 'BOLT ', ''), ' ATTACH', '') AS JU_COUNT1
    FROM [dbo].[SUPPORTSTRUCTURE]
)

SELECT
    SUBSTRING(JU_COUNT1, 1, CHARINDEX(' ', JU_COUNT1) - 1) AS BOLT,
    SUBSTRING(JU_COUNT1, CHARINDEX(' ', JU_COUNT1) + 1,
              LEN(JU_COUNT1) - CHARINDEX(' ', JU_COUNT1)) AS ATTACH
FROM cte;

在此处输入图片说明

Demo

An approach without cte is this

declare @JU_COUNT1 table (data varchar(20))

insert into @JU_COUNT1 (data) values  
('1 BOLT 4 ATTACH'),
('2 BOLT 2 ATTACH'),
('3 BOLT 1 ATTACH'),
('0 BOLT 3 ATTACH'),
('2 BOLT 10 ATTACH'),
('2 BOLT 12 ATTACH')

select left(data, charindex(' BOLT', data) - 1) as Bolt,
       right(replace(data, ' ATTACH', ''), len(replace(data, ' ATTACH', '')) - (charindex('BOLT', replace(data, ' ATTACH', '')) + 4)) as Attach
from @JU_COUNT1 

result is

Bolt    Attach  
----    ------- 
1       4   
2       2   
3       1   
0       3   
2       10  
2       12  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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