简体   繁体   中英

T-SQL: Concat multiple rows value in into one value

I make an example using CTE and here it is

with CTE as
(
Select 'John' as Name, 'Book' as Product
Union all
Select 'John' as Name, 'Pen' as Product
Union all
Select 'John' as Name, 'Phone' as Product
Union all
Select 'Kevin' as Name, 'Book' as Product
Union all
Select 'Kevin' as Name, 'Watch' as Product
) 

SELECT Name, Product=STUFF(
             (SELECT ';' + Product FROM CTE t2
              WHERE t1.Name = t2.Name 
              FOR XML PATH ('')) , 1, 1 , '')
FROM CTE t1
GROUP BY Name

If you first just

select * from CTE 

then you will see how the original data look like

This is one way I found on Internet but first I don't understand how it works, if someone can explain how this work I am very much appreciated Second, are there easier ways to achieve my goal?

thanks!

First off, this is the best way to do what your trying to do. It's very efficient especially compared to other methods. Let me explain how it works.

--So first your group by is grouping by name. 
    --It's really just getting the DISTINCT values of name
    --You could actually use a distinct name instead of the group by clause
SELECT  Name, 
        Product = 
                (
                --This combines your semicolon to each value of product
                SELECT ';' + Product 
                FROM CTE t2
                --This connects this subquery to the outer query
                WHERE t1.Name = t2.Name 

                --I don't know how this works exactly. It obviously uses some kind of XML parsing, but it concats all your rows together into one
                FOR XML PATH ('')
                )
FROM CTE t1
GROUP BY Name

Results:

Name  Product
----- ----------------
John  ;Book;Pen;Phone
Kevin ;Book;Watch

You'll notice I got rid of STUFF() to show you that all it does is remove the first semicolon. You could use SUBSTRING() instead if you wanted to.

Hope this helps. Let me know if you need anything else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM