SQL多行并一行统计例子之STUFF()函数+FOR XML PATH()函数应用

SELECT * FROM tbiz_ProjectRelation

SQL多行并一行统计例子之STUFF()函数+FOR XML PATH()函数应用

目标统计每个项目有几条申请记录

Step1

SELECT  ProjectID ,
RelationIDs = STUFF(( SELECT ',' + CONVERT(VARCHAR,[RelationID]) FROM tbiz_ProjectRelation t WHERE ProjectID = t1.ProjectID FOR XML PATH('')), 1, 1, '')
FROM tbiz_ProjectRelation t1

Step2

SELECT  ProjectID ,
RelationIDs = STUFF(( SELECT ',' + CONVERT(VARCHAR,[RelationID]) FROM tbiz_ProjectRelation t WHERE ProjectID = t1.ProjectID FOR XML PATH('')), 1, 1, '')
FROM tbiz_ProjectRelation t1 GROUP BY ProjectID

Step3

SELECT  ProjectID ,
RelationIDs = STUFF(( SELECT ',' + CONVERT(VARCHAR,[RelationID]) FROM tbiz_ProjectRelation t WHERE ProjectID = t1.ProjectID FOR XML PATH('')), 1, 1, ''),
COUNT([RelationID]) AS [COUNT]
FROM tbiz_ProjectRelation t1 GROUP BY ProjectID

SQL多行并一行统计例子之STUFF()函数+FOR XML PATH()函数应用

上一篇:SQL 多行合并一行


下一篇:SQL实现多行合并一行 .