Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combining table column in SQL Server

I have to combine the Customer_address when they have the same address_index but different line_nbr:

CUSTOMER_NUM CUSTOMER_CODE CUSTOMER_ADDRSS LINE_NBR ADDRESS_INDEX ADDRESS_CODE
31 GEW 3901 Castle Hayne Road 17 1 SHIP
30 GEW Highway 117 N 18 1 SHIP
212 GEW 1005 2nd Street 19 2 SHIP
23 GEW 3901 Castle Hayne Road 20 3 SHIP
241 GEW Highway 117 N 21 3 SHIP
360 GEW 465 McCarthy Road 1 4 SHIP
469 GEW 3901 Castle Hayne Road 1 5 SHIP
470 GEW Highway 117 N 2 5 SHIP

I need to combine CUSTOMER_NUM 31 and 30 to read

Castle Hayne Road Highway 117 N

By combining Address_index = 1 with Line_nbr 17 and 18, and also Address_index = 3 with line_nbr 20 and 21, and Address_index 5 with line_nbr 1 and 2, etc….

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

New to SQL and trying to figure out how to link the two columns together and write out the customer address in one column instead of the two rows it currently resides.

Thanks!

>Solution :

On SQL Server 2017+, STRING_AGG() makes this easy:

SELECT CUSTOMER_CODE, 
       MergedAddress = STRING_AGG(CUSTOMER_ADDRSS, ' ') 
                       WITHIN GROUP (ORDER BY LINE_NBR)
  FROM dbo.MyTable
  GROUP BY CUSTOMER_CODE, ADDRESS_INDEX;

Output:

CUSTOMER_CODE MergedAddress
GEW 3901 Castle Hayne Road Highway 117 N
GEW 1005 2nd Street
GEW 3901 Castle Hayne Road Highway 117 N
GEW 465 McCarthy Road
GEW 3901 Castle Hayne Road Highway 117 N

On older versions, you’re going to have to use more cumbersome and inefficient methods like this:

SELECT CUSTOMER_CODE, 
       MergedAddress = RTRIM((SELECT CUSTOMER_ADDRSS + ' '
         FROM dbo.MyTable AS inside
         WHERE inside.ADDRESS_INDEX = outside.ADDRESS_INDEX
         ORDER BY LINE_NBR
         FOR XML PATH(''), TYPE).value(N'./text()[1]', N'varchar(max)'))
  FROM dbo.MyTable AS outside 
  GROUP BY CUSTOMER_CODE, ADDRESS_INDEX;

The example db<>fiddle shows the results and also the plans that should help explain why the latter is so bad.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading