Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HTML
Table
Column1	Column2
a	      1
a	      2
a	      3
a	      4
a	      5
a	      6
a	      7
a	      8
a	      9
a	      10

HTML
 Required OUT PUT: 
Column1	Column2
a	       1,2,3,4,5
a	        6,7,8,9,10


What I have tried:

I have tried to get below result using sql server but don't get excepted result.
Please help.
Posted
Updated 20-Feb-17 23:30pm

1 solution

Check this:
sql - Concatenate many rows into a single text string? - Stack Overflow[^]
sql - Multiple rows to one comma-separated value - Stack Overflow[^]


[EDIT]
I forgot to mentiond that you need to use NTILE(2)[^] function to be able to split Column1 into 2 groups, before you start concatenating Column2:
SQL
SELECT *, NTILE(2) OVER( ORDER BY Column1) AS GrpNo
FROM YourTableName


Complete example:
SQL
DECLARE @tmp TABLE (Column1 VARCHAR(5),	Column2 INT)

INSERT INTO @tmp (Column1, Column2)
VALUES('a', 1),
('a', 2),
('a', 3),
('a', 4),
('a', 5),
('a', 6),
('a', 7),
('a', 8),
('a', 9),
('a', 10)

SELECT DISTINCT t2.Column1, 
    (
        SELECT CONVERT(VARCHAR(100), t1.Column2) + ',' AS [text()]
        From (
			SELECT *, NTILE(2) OVER( ORDER BY Column1) AS GrpNo
			FROM @tmp
		) t1
        WHERE t1.Column1  = t2.Column1 AND t1.GrpNo = t2.GrpNo
        FOR XML PATH ('')
    ) AS Col2
FROM (
	SELECT *, NTILE(2) OVER( ORDER BY Column1) AS GrpNo
	FROM @tmp
	) AS t2
 
Share this answer
 
v4
Comments
suneel kumar gupta 22-Feb-17 0:45am    
I have to define the max no of elements in each group.
For Eg: IF no's from 1 to 25 and if Max element in each group is 10,
then o/p s'd be

a 1,2,3..10
b 11,12,...20
c 21,22...25
Maciej Los 22-Feb-17 1:57am    
And?
Have you read about NTILE function?
Have you tried to change the sample to your needs?
suneel kumar gupta 22-Feb-17 4:31am    
Thank you I got it.
Maciej Los 22-Feb-17 6:47am    
You're very welcome. Please, accept my solution (green button).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900