SQL for splicing and splitting characters

1. When processing data queries, sometimes you need to merge multiple rows of data into one row, or split the data in one row. Let's take a look at the example:

If you have a set of data:

 ID         name

1212 Big suit

1212 small suit

We need to display the results as:

  ID             name

1212 Big suit, small suit

Create test data:

select * from #2
DROP TABLE #2
create table #2
(id int,
 name nvarchar(max))
insert into #2
select 1212,N'小西装' union all

select 1212, N'big suit '

Implementation:

select id,

(STUFF((select ','+name from #2 a where a.id=b.id for xml path ('')),1,1,''))as name

 from #2 b

 group by id

Remarks:

1. The calculated column can be displayed directly without being included in the aggregate function, such as val in the following statement.
2. for xml path ('') should be applied at the end of the statement, and then generate xml.
3. The path parameter in for xml path ('root') is the top-level node of the generated xml.
4. The field name or alias will become a child node of xml, and the field without column name (field + '') or without alias will be displayed directly. For example, [value] + ',' is data separated by (aa, bb,).
5. Use self-linking when combining multiple rows of data to display as one row of data.
 STUFF: delete a character specified length, and inserted into a set of characters starting at the specified
syntax:
STUFF is (character_expression, Start, length, character_expression)
such as: SELECT STUFF ( 'abcdef', 2, 3, 'ijklmn')
  below Is the result set: aijklmnef


The above achieves the effect of parallel connection, but if your own value is parallel, how to split it?

Create test data:

create table # 2 (id int, name Nvarchar (100))
insert into # 2 values ​​(1212, N'Small suit, big suit ')

Implementation code:

SELECT A.id, B.name
FROM(
    SELECT id, [name] = CONVERT(xml,' <root> <v>' + REPLACE([name], ',', ' </v> <v>') + ' </v> </root>') FROM #2
)A
OUTER APPLY(
    SELECT name = N.v.value('.', 'varchar(100)') FROM A.[name].nodes('/root/v') N(v)
)B

 Result set:

ID              name

1212 Big suit

1212 small suit

 

 

 

Published 22 original articles · praised 7 · 100,000+ views

Guess you like

Origin blog.csdn.net/qyx0714/article/details/70175486