在sql server中组合来自muliple行的字符串

时间:2017-07-17 05:56:58

标签: sql sql-server sql-server-2012

如何在sql server 2012中获取以下输出。

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

输出应该是第一行具有固定数量的值(2),用逗号分隔,下一行的剩余值用逗号分隔

ID

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

每个id应在一行中包含最多两个值。其余值应包含在下一行中。

1 个答案:

答案 0 :(得分:1)

尝试使用我的代码:

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]