开发者社区> 问答> 正文

如何为 SQL 服务器中的多个列使用 stuff 函数?

如何为 SQL 服务器中的多个列使用 stuff 函数?

展开
收起
贺贺_ 2019-12-17 16:59:59 1424 0
1 条回答
写回答
取消 提交回答
  • 您可以执行以下操作。只需按这些列分组,并为串联列进行 2 个子选择:

    select UserID, 
           ConductedByID, 
           QuestionID, 
    
           (SELECT STUFF((SELECT ';' + Response
                          FROM TableName tn2 WHERE tn1.UserID = tn2.UserID and 
                                         tn1.ConductedByID = tn2.ConductedByID and
                                         tn1.QuestionID = tn2.QuestionID and 
                                         tn1.ParticipantID = tn2.ParticipantID
                FOR XML PATH('')) ,1,1,'')) as Response,
    
           (SELECT STUFF((SELECT ';' + cast(Rating as varchar)
                          FROM TableName tn2 WHERE tn1.UserID = tn2.UserID and 
                                         tn1.ConductedByID = tn2.ConductedByID and
                                         tn1.QuestionID = tn2.QuestionID and 
                                         tn1.ParticipantID = tn2.ParticipantID
                FOR XML PATH('')) ,1,1,'')) as [Response Rating],
    
           AVG(case when Rating = 'n/a' then 0 else cast(Rating as int) end) as [Rating Avg], 
           ParticipantID
    from TableName tn1
    group by UserID, ConductedByID, QuestionID, ParticipantID
    
    2019-12-17 17:00:18
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
SQL Server 2017 立即下载
GeoMesa on Spark SQL 立即下载
原生SQL on Hadoop引擎- Apache HAWQ 2.x最新技术解密malili 立即下载