How to combine/merge multiple rows into a single rows as a list in SQL.
[original Scenario:]
[Required Scenario:]
How to combine/merge multiple rows into a single rows as a list in SQL.
[original Scenario:]
[Required Scenario:]
SQL Server provides ROW_NUMBER()
function to achieve the above
SELECT CASE WHEN ROW_NUMBER() OVER(PARTITION BY [column1] ORDER BY [column1]) > 1
THEN ''
ELSE CAST([column1] AS VARCHAR)
END [column1],
[column2]
FROM <table>;
EDIT : use of STUFF()
function
select
[column1],
[column2] = stuff(
(select DISTINCT ' '+[column2] from <table> where [column1] = t.[column1] for xml path('')),
1,1, ''
)
from <table> t group by [column1]
Result :
column1 column2
1 Value 1 Value 2 Value 3
2 Value 4
3 Value 5 Value 6
thanks @Yogesh For your help !!
I have used the below query and it is working fine for me and displays the data as requiredrequired Scenario:
Select distinct ST2.SubjectID,
substring(
(
Select CHAR(10) +ST1.StudentName AS [text()]
From dbo.Students ST1
Where ST1.SubjectID = ST2.SubjectID
ORDER BY ST1.SubjectID
For XML PATH ('')
), 2, 1000) [Students]
From dbo.Students ST2