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

Posted 轴轴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL多行并一行统计例子之STUFF()函数+FOR XML PATH()函数应用相关的知识,希望对你有一定的参考价值。

SELECT * FROM tbiz_ProjectRelation

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

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 将查询结果为多行一列合并为一行一列

sql查询 ,多行数据合并成一行,并且显示合并后某一列的值拼接结果

T-SQL 合并多行数据显示到一行

合并多行查询数据到一行:使用自连接FOR XML PATH('')STUFF或REPLACE函数

Oracle sql使用子查询将多行结果分组为一行