我有下表:
RECID OBJECTIF
1001 1001
1001 1002
1001 1003
2001 2001
2001 2002
我需要这样的结果:
RECID MyFIELD
1001 1001-1002-1003
2001 2001-2002
如果您能给我一个使用内容的提示,则无需编写代码
请考虑到我的表中有数百万条记录
感谢
答案 0 :(得分:2)
你走了......我不确定数百万条记录的表现......但我觉得这比基于游标的方法更好....
SELECT * FROM [PivotSample]
RECID OBJECTIFSEQUENCE
1001 1002 1
1001 1003 3
1001 1001 2
2001 2001 3
2001 2002 4
2001 2003 2
2001 2004 1
下面给出了答案查询..
SELECT [RECID]
,STUFF((SELECT '- ' + CAST([OBJECTIF] AS varchar), REPLACE(MAX(SEQUENCE),MAX(SEQUENCE),'') FROM [PivotSample] B WHERE B.[RECID]=A.[RECID]
GROUP BY [OBJECTIF],SEQUENCE ORDER BY SEQUENCE FOR XML PATH('')), 1, 1, '' ) AS OBJECTIVE
FROM [PivotSample] A
GROUP BY [RECID]
RECID OBJECTIVE
1001 1002- 1001- 1003
2001 2004- 2003- 2001- 2002