开发者社区> 问答> 正文

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

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

展开
收起
贺贺_ 2019-12-17 16:59:59 1450 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
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
如何运维千台以上游戏云服务器 立即下载
网站/服务器取证 实践与挑战 立即下载
ECS计算与存储分离架构实践 立即下载