2016-12-06 12 views
1
declare @t table 
(
    year int, 
    month int, 
    SomeName varchar(100) 
) 

insert into @t 
select 2015, 1, 'Ashok' 
union 
select 2015, 2, 'Ram' 
union 
select 2015, 3, 'Ashok' 
union 
select 2016, 1, 'Raj' 
union 
select 2016, 2, 'Raj' 

select * from @t 

上記の選択は私に次のように返します。私は以下のように取得するにはどうすればよいSQLの文字列値の累積連結でグループを取得する方法

year month SomeName 
2015 1  Ashok 
2015 2  Ram 
2015 3  Ashok 
2016 1  Raj 
2016 2  Raj 

..

year month name CumSrome 
2015 1  Ashok Ashok 
2015 2  Ram  Ashok,Ram 
2015 3  Ashok Ashok,Ram 
2016 1  Raj  Raj 
2016 2  Raj  Raj 

TIA

+0

あなたは* ...これは今年でグループ化されている*累積について話していますか? 'ラジーズ'だけはなぜ? – Shnugo

+0

希望の結果を得る方法を説明してください – GuidoG

答えて

4

このようにそれを試してみてください。

declare @t table 
(
    year int, month int, 
    SomeName varchar(100) 
); 

insert into @t 
select 2015, 1, 'Ashok' 
union all 
select 2015, 2, 'Ram' 
union all 
select 2015, 3, 'Ashok' 
union all 
select 2016, 1, 'Raj' 
union all 
select 2016, 2, 'Raj'; 

SELECT t.* 
     ,CumumlativeConcatPerYear.Names 
FROM @t AS t 
CROSS APPLY 
(
    SELECT STUFF(
    (
     SELECT DISTINCT ', ' + SomeName 
     FROM @t AS x 
     WHERE x.year=t.year AND x.month<=t.month 
     FOR XML PATH('') 
    ),1,2,'') 
) AS CumumlativeConcatPerYear(Names) 
0

へのXML PATHコマンドのと組み合わせSTUFFコマンドを使用します文字列を連結します。

https://sqlwhisper.wordpress.com/2013/03/24/stuff-and-for-xml-path-for-string-concatenation/

+0

これはコメントであり、答えではありません。はい、それは役に立ちますが、それはOPが見つけて答えるのに役立ち、それ自体は答えがありません – GuidoG

+0

申し訳ありません、私は9日間だけ投稿していますが、このサイトの仕組みについて学ぶためにまだたくさんあります。 – pacreely

関連する問題