SQL function merge columns in multiple rows into one row and one column

Source: Internet
Author: User

Copy codeThe Code is as follows:
Create table tb (standards varchar (50), amount varchar (50), variation varchar (50), statuss varchar (50), Reason varchar (50 ))
Insert into tb values ('55', '123456', '4', 'backlog of things ', 'Insufficient processing staff and equipment; slow T-sorting ;')
Insert into tb values ('55', '000000', '4', 'overstocked things ', 'Insufficient parts ;')
Insert into tb values ('55', '000000', '4', 'amount backlog ', 'cross-site backlog; many drawing problems ;')
Insert into tb values ('56 ', '123456', '4', 'item backlog', 'aaaa ;')
Insert into tb values ('56 ', '000000', '4', 'overstocked things', 'bbbb ;')
Insert into tb values ('56 ', '123456', '4', 'item backlog', 'cccc ;')

Create function test (@ standards varchar (100 ))
Returns varchar (8000)
As
Begin
Declare @ re varchar (500)
Set @ re =''
Select @ re = @ re + ',' + Reason
From tb
Where @ standards = standards
Return (stuff (@ re, 1,1 ,''))
End

Call
Copy codeThe Code is as follows:
Select distinct standards, amount, variation, statuss, Reason = dbo. test ('55') from tb where standards = 55
Select distinct standards, amount, variation, statuss, Reason = dbo. test ('56') from tb where standards = 56

Related Article

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.