-1

I have a table with single column Countries as:

Countries

USA
USA
France
India
USA
Russia
France
India

I want to concatenate distinct values in a single row like

Countries

USA,France,India,Russia

How do I write SQL query to achieve the same?

Thanks in advance.

Ashish
  • 21
  • 4
  • While asking a question, you need to provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example): (1) DDL and sample data population, i.e. CREATE table(s) plus INSERT T-SQL statements. (2) What you need to do, i.e. logic and your code attempt implementation of it in T-SQL. (3) Desired output, based on the sample data in the #1 above. (4) Your SQL Server version (SELECT @@version;). – Yitzhak Khabinsky Aug 10 '22 at 12:22
  • 1
    Does this answer your question? [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) – SMor Aug 10 '22 at 12:23

2 Answers2

2
WITH CTE(COUNTRY)AS
(
  SELECT 'USA' UNION ALL
  SELECT'USA'UNION ALL
  SELECT'France'UNION ALL
  SELECT'India'UNION ALL
  SELECT'USA'UNION ALL
  SELECT'Russia'UNION ALL
  SELECT'France'UNION ALL
  SELECT'India'
)
SELECT STRING_AGG(C.COUNTRY,',')
FROM 
(
   SELECT DISTINCT COUNTRY FROM CTE
)C
Sergey
  • 4,719
  • 1
  • 6
  • 11
0

If its from a table Country and fieldName is CountryName, then below query would do good, SELECT STRING_AGG(CountryName) FROM (SELECT DISTINCT CountryName FROM Country). Incase if you are using older version of SQL, STUFF can be used to achieve the output.