Multiple rows to one comma-separated value different ID
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
╔════╦═════════════════════╗
║ ID ║ List_Output ║
╠════╬═════════════════════╣
║ 1 ║ 100, 200, 300, 400 ║
╚════╩═════════════════════╝
How to show data from multiple rows into single row as comma separated string
Modification:
If your SQL Server version is 2017 or above then you can use string_agg() to achieve your desired result. It's way too much faster than stuff() with For XML PATH()
with cte as
(SELECT Books.Name BookName, Categories.Name CategoryName FROM Books_Categories
INNER JOIN Books ON Books.Id = Books_Categories.BookId
INNER JOIN Categories ON Categories.Id = Books_Categories.CategoryId)
SELECT t.BookName,STRING_AGG(CategoryName,',') CategoryName
FROM cte t
GROUP BY t.BookName
You can achieve this in sql-server older than 2017 by using STUFF() with For XML PATH
Schema:
CREATE TABLE [dbo].[books](
[id] [int] NULL,
[name] [varchar](50) NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[categories](
[id] [int] NULL,
[name] [varchar](50) NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[Books_Categories](
[id] [int] NULL,
[bookid] [int] NULL,
[categoryid] [int] NULL
) ON [PRIMARY]
Insert statements:
insert into books values(1,'BookA');
insert into books values(2,'BookB');
insert into categories values(1,'CategoryA');
insert into categories values(2,'CategoryB');
insert into Books_Categories values(1, 1, 1);
insert into Books_Categories values(2, 1, 2);
insert into Books_Categories values(3, 2, 2);
Query#1 (STUFF() and For XML PATH():
with cte as
(SELECT Books.Name BookName, Categories.Name CategoryName FROM Books_Categories
INNER JOIN Books ON Books.Id = Books_Categories.BookId
INNER JOIN Categories ON Categories.Id = Books_Categories.CategoryId)
SELECT t.BookName
, STUFF(( SELECT ', ' + CategoryName
FROM cte
WHERE BookName = t.BookName
FOR XML PATH(''),TYPE)
.value('.','NVARCHAR(MAX)'),1,2,'') AS CategoryName
FROM cte t
GROUP BY t.BookName
GO
Query#2 (using string_agg() for SQL Server 2017(14x) and later):
with cte as
(SELECT Books.Name BookName, Categories.Name CategoryName FROM Books_Categories
INNER JOIN Books ON Books.Id = Books_Categories.BookId
INNER JOIN Categories ON Categories.Id = Books_Categories.CategoryId)
select t.bookname,string_agg(categoryname,',') CategoryName from cte t
GROUP BY t.BookName
Output:
BookName | CategoryName |
---|---|
BookA | CategoryA, CategoryB |
BookB | CategoryB |
Multiple rows to one comma-separated value in sql
Use where clause :
select name , STUFF((SELECT '; ' + facilty
FROM leads
FOR XML PATH('')
),1,2,'') as facilty, address
from leads
where name is not null;
Multiple rows to one comma-separated value in Sql Server
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
╔════╦═════════════════════╗
║ ID ║ List_Output ║
╠════╬═════════════════════╣
║ 1 ║ 100, 200, 300, 400 ║
╚════╩═════════════════════╝
SQL Server 2017 and Later Versions
If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:
DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);
SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;
Result Set
╔════╦═════════════════════╗
║ ID ║ List_Output ║
╠════╬═════════════════════╣
║ 1 ║ 100, 200, 300, 400 ║
╚════╩═════════════════════╝
Convert multiple rows into a single comma separated string without XML
Convert multiple rows into one with comma as separator
This should work for you. Tested all the way back to SQL 2000.
create table #user (username varchar(25))
insert into #user (username) values ('Paul')
insert into #user (username) values ('John')
insert into #user (username) values ('Mary')
declare @tmp varchar(250)
SET @tmp = ''
select @tmp = @tmp + username + ', ' from #user
select SUBSTRING(@tmp, 0, LEN(@tmp))
Related Topics
How to Get the Numeric Part from a String Using T-Sql
Best Way to Iterate Through Columns in a SQL Table
How to Calculate Percentage Between Two Numbers Using SQL on Bigquery
Select Only Rows With Max Date
Query to Get All Those Names of Employees,Who Have 'A' as Their Middle Character in Their Name
Select Rows Within Last Complete Minute
Phpmyadmin Says No Privilege to Create Database, Despite Logged in as Root User
How to Strip All Non-Alphabetic Characters from String in SQL Server
Explode and Implode Strings in MySQL Query
Comparing Two Count Results Using SQL
Getting Two Counts and Then Dividing Them
Number of Times a Value Appears (Sql)
How to Return a Flag If Exist Id in Another Table MySQL
Constraint for Phone Number in SQL Server
Sql Query for Values Consisting of Only a Specific Character
Solve Query for Showing Top 5 Selling Products
How to Store the Select Statement Output into Variable Thro Psql ( Postgresql )