sql-server - 如何通过累积连接获取 SQL 中字符串值的分组

标签 sql-server database tsql sql-server-2012 logic

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/

相关文章:

sql - Postgres 架构问题

SQL选择startdate是今天的日期

sql - 将 varchar 值转换为 smallint 数据类型时转换失败

sql-server - 具有 varchar 值的数据透视表

SQL Server 2005 - 同步开发/生产数据库

php - MySQL:将未加密的密码列转换为 MD5 哈希

sql - 从包含 : For each row in a different table call a table returning function 的表中选择

SQL 服务器 2012 : Add a linked server to PostgreSQL

sql - 如何在聚合函数 SQL Server 中有一个 where 子句

android快捷方式,访问启动器数据库