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
上面的选择返回以下内容。
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
最佳答案
像这样尝试:
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)
关于sql-server - 如何通过累积连接获取 SQL 中字符串值的分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40991990/