Merge two columns in multiple rows and remove duplicate Columns

Source: Internet
Author: User
-- Merge two columns in multiple rows and remove duplicate columns:

Create Table TB
(Col1 varchar (10 ),
Col2 varchar (10 ),
Col3 varchar (10 ),
Col4 varchar (10 ))
Go

Insert TB select '200', '200', 'A', 1
Insert TB select '200', '200', 'A', 1
Insert TB select '200', '200', 'B', 2
Insert TB select '200', '200', 'B', 2

Go
Create Function DBO. f_str (@ col3 varchar (10 ))
Returns varchar (8000)
As
Begin
Declare @ STR varchar (8000)
Set @ STR =''
Select @ STR = @ STR +
Case
When charindex (',' + col1 + '-', ',' + @ STR + '-') = 0 then col1 + '-'
Else''
End +
Case
When charindex ('-' + col2 + ',', '-' + @ STR + ',') = 0 then col2 + ','
Else''
End
From TB
Where col3 = @ col3
Return
Left (@ STR, Len (@ Str)-1)
End
Go
Select distinct newcol = DBO. f_str (col3), col3, col4 from TB

Drop table TB
Drop function f_str

/*
Newcol col3 col4
--------------------------------------
11111-222,1111-333 A 1
2222-999,3333-111 B 2
*/


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.