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

Source: Internet
Author: User

Project requirements: Multiple rows of data in a table are displayed in a single field, as follows:

For example, there are field id,name in Table A,

There are field id,pid,des in table B,

Table A, the data in table B are as follows:

ID NAME
1 sheets of three
2 John Doe

ID PID DES
11 languages
21 Mathematics
31 Foreign languages
42 History
52 geography

Finally I want to show the effect as:

ID NAME KC
1 three languages, mathematics, foreign languages
2 Li four History, geography

Method: Use the stuff function in SQL with the FOR XML path

The 1.for XML path is an XML representation of the query result set

For example, table B,select * from B FOR XML path (")

The resulting set of results is as follows:

<ID>1</ID><PID>1</PID><DES> languages </DES><ID>2 </ID><PID>1</PID><DES> math </DES><ID>3</id><pid >1</PID><DES> Foreign Languages </DES><ID>4</ID><PID>2</ Pid><des> history </DES><ID>5</ID><PID>2</PID><DES> Geography </DES>
View Code

Here the dataset is not shown as multi-row data

The 2.stuff function is used as: stuff (param1, startIndex, length, param2)
Note: Remove the length characters from the param1 in startindex (all SQL starts with 1, not 0), and then replace the deleted characters with param2.

Therefore, the format of converting multiple rows of data to one line is:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.