0

In SQL my query results are like

enter image description here

I need to get results with my product name appended with ',' so that contact names are not duplicated.

Please help.

Bokbob
  • 89
  • 1
  • 9
  • 2
    Possible duplicate of [How to concatenate text from multiple rows into a single text string in SQL server?](https://stackoverflow.com/questions/194852/how-to-concatenate-text-from-multiple-rows-into-a-single-text-string-in-sql-serv) – Vinit Jul 19 '18 at 01:35
  • which DBMS is it? could you please tag – Vinit Jul 19 '18 at 01:36
  • 1
    When you added the SQL tag, a **large message** was shown to you that suggested that you also add a tag for the specific DBMS you're using, because the syntax and functionality between them differs. Why did you choose to ignore that suggestion? By doing so you've made it take longer for you to get an answer (because we have to wait for you to add it), as well as wasting the time of people who try to help only to find out it won't work for you because you're using a different DBMS. – Ken White Jul 19 '18 at 02:06
  • RDBMS.Transact SQL. Sorry i didn'd think it would be waste of anyones time. – Bokbob Jul 19 '18 at 03:25

2 Answers2

1

My Above answer is not applicable to older versions than SQL-Server 2017. So I have implemented some other solution as below.

Sample table: your_table

enter image description here

And apply this code:

select distinct tb2.first_name, 
    substring(
        (
            select ','+tb1.product_name  as [text()]
            from dbo.your_table as tb1
            where tb1.first_name = tb2.first_name
            order by tb1.first_name
            for xml path ('')
        ), 2, 500) [products]
from dbo.your_table tb2;

The result is here as per the expectations:

enter image description here

Irfan
  • 665
  • 6
  • 29
0

SQL-Server 2017 (Not introduced for earlier versions)

Use string aggregation function STRING_AGG().

SELECT first_name+''+last_Name, STRING_AGG(product_name, ', ') AS products
FROM your_table
GROUP BY first_name,last_Name;

Add columns in GROUP BY according to your required output. Hope this will help you.

Irfan
  • 665
  • 6
  • 29