Concatenation 连接多行SQL Server

Concatenation 连接多行SQL Server,concatenation,sql-server-2014,Concatenation,Sql Server 2014,如何按特定顺序合并一个字段中的数据行 field A --------- 301 301 301 field B ------- 1 2 3 field C ------- abc 123 def 预期结果: field A ------- 301 field C ------- abc -- 123 -- def 我是一个使用SQL Server 2014的完全初学者,所以请让它简洁明了 非常感谢 凯文 每组是否始终有三行数据? CR

如何按特定顺序合并一个字段中的数据行

field A         
---------
301 
301 
301

field B    
-------
1
2
3       

field C
-------
abc
123
def   
预期结果:

field A
-------
301

field C
-------
abc -- 123 -- def
我是一个使用SQL Server 2014的完全初学者,所以请让它简洁明了

非常感谢

凯文


每组是否始终有三行数据?
CREATE TABLE #Temp
(
    fieldA int,
    fieldB int,
    fieldC varchar(3)
)

INSERT INTO #Temp (fieldA,fieldB,fieldC)
VALUES  (301,1,'abc'),
        (301,2,'123'),
        (301,3,'def'),
        (302,1,'ghi'),
        (302,2,'456'),
        (302,3,'jkl')
;
--Start of query to use with your data

--Common Table Expression to get the Row Numbers for fieldA
WITH preselect AS
(SELECT ROW_NUMBER() OVER(PARTITION BY fieldA ORDER BY fieldA)'RowNum',*
        FROM #Temp)--change #Temp to your table name

SELECT a.fieldA,a.fieldC +' -- '+ b.fieldC +' -- '+ c.fieldC 'Combined Field C '
FROM preselect a --Self Joins to pivot the data                                     
     JOIN preselect b ON a.fieldA = b.fieldA AND b.RowNum = 2
     JOIN preselect c ON a.fieldA = c.fieldA AND c.RowNum = 3
WHERE a.RowNum = 1

--End of query to use with your data

DROP TABLE #Temp