1

How can I obtain the below output in sql server 2012.

Table

ID  | Values|
1      a  
1      b    
1      c   
2      d      
2      e 

The output should be such that the first row has a fixed number of values(2) seperated by comma and the next row has the remaining values seperated by comma

ID

ID  | Values|
1      a,b  
1      c    
2      d,e   

Each id should contain maximum two values in a single row.The remaining values should come in the next row.

3
  • 1
    Have you tried something yet? Commented Jul 17, 2017 at 6:01
  • 1
    How come you want (a,b) and c, instead of (a,c) and b, or (b,c) and a? Commented Jul 17, 2017 at 7:08
  • I think this needs a little more context to provide any real/helpful answers Commented Jul 17, 2017 at 7:26

1 Answer 1

1

Try to use my code:

use db_test;

create table dbo.test567
(
    id int,
    [values] varchar(max)
);

insert into dbo.test567
values 
    (1, 'a'),
    (1, 'b'),
    (1, 'c'),
    (2, 'd'),
    (2, 'e')

with cte as (
    select 
        id, 
        [values], 
        row_number() over(partition by id order by [values] asc) % 2 as rn1,
        (row_number() over(partition by id order by [values] asc) - 1) / 2 as rn2
    from dbo.test567
), cte2 as (
select 
    id, max(case when rn1 = 1 then [values] end) as t1, max(case when rn1 = 0 then [values] end) as t2
from cte
group by id, rn2
)
select 
    id, 
    case 
        when t2 is not null then concat(t1, ',', t2)
        else t1
    end as [values]
from cte2
order by id, [values]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.