Based on this sample table
ID | NAME | ZIP | NTID |
---|---|---|---|
1 | Juan | 123 | H1 |
1 | Juan | 123 | H2 |
2 | John | 456 | H3 |
2 | John | 456 | H4 |
2 | John | 456 | H5 |
I want to show ntid
as a comma separated value but in groups of maximum 2 items
Expected result
ID | NAME | ZIP | NTID |
---|---|---|---|
1 | Juan | 123 | H1, H2 |
2 | John | 456 | H3, H4 |
2 | John | 456 | H5 |
Using SQL Server, is there a way to achieve this?
By using the STRING_AGG
function it concatenates all in a single row, but I need to group as groups of maximum of 2 members.
SELECT ID, NAME, ZIP, STRING_AGG(NTID,',')
FROM MyTable
GROUP BY ID, NAME, ZIP
So you can use a modified row number (divided by 2) to group your data into blocks of 2 rows, and then you can use string_agg()
.
You do need a way to order the rows though (if you want consistent results), I have assumed NTID
will work, but you may have a better column to order by.
declare @Test table (ID int, [NAME] varchar(32), ZIP varchar(12), NTID varchar(2));
insert into @Test (ID, [NAME], ZIP, NTID)
values
(1, 'Juan', '123', 'H1'),
(1, 'Juan', '123', 'H2'),
(2, 'John', '456', 'H3'),
(2, 'John', '456', 'H4'),
(2, 'John', '456', 'H5');
with cte as (
select *
, (row_number() over (partition by ID order by NTID) - 1) / 2 rn
from @Test
)
select ID, [NAME], string_agg(NTID,',')
from cte
group by ID, [NAME], rn;
db<>fiddle here
Note: If you supply the DDL+DML as part of your question you make it much easier to answer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.