Display multiple rows of data in a table in one field in SQL

Project requirements: Display multiple rows of data in a table in one field, as follows:

For example, table A has fields ID, NAME,

Table B has fields ID, PID, DES,

The data in Table A and Table B are as follows:

ID NAME
1 Zhang San
2 Li Si

ID PID DES
1 1 Language
2 1 Mathematics
3 1 Foreign Language
4 2 History
5 2 Geography

Ultimately what I want to display is:

ID NAME KC
1 Zhang SanLanguage, Mathematics, Foreign Language
2 Li Si History, Geography

Method: Use the STUFF function in sql with for xml path

 1. For xml path is to display the query result set in XML form

For example, for table B, select * from b for xml path('')

The result set obtained is as follows:

<ID>1</ID>
<PID>1</PID>
<DES>Language</DES>
<ID>2</ID>
<PID>1</PID>
<DES>Math</DES>
<ID>3</ID>
<PID>1</PID>
<DES>Foreign Language</DES>
<ID>4</ID>
<PID>2</PID>
<DES>History</DES>
<ID>5</ID>
<PID>2</PID>
<DES>Geography</DES>

This dataset is not presented as multi-row data

2. The usage of the stuff function is: stuff(param1, startIndex, length, param2)
Description: delete the length characters from startIndex (in SQL all start from 1, not 0) in param1, and then replace the deletion with param2. dropped characters.

Therefore, the format for converting multiple lines of data into one line is:

select ID as ID,Name as NAME,
(select stuff((select ','+DES from b where b.PID=a.ID for xml path('')),1,1,'')) as KC
from a

 

Original source: https://www.cnblogs.com/IceNewMan/p/5707470.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324803793&siteId=291194637