如何在SQL Server中为多列使用stuff函数?

时间:2015-06-05 15:50:53

标签: sql sql-server sql-server-2008

我需要连接具有相同Id的两行的两个值,并为其他列连接平均值。这是我的样本表:

enter image description here

现在我的要求是,我需要连接Response列,连接Response Rating列并平均Rating Avg列,如果它具有相同的ParticipantId, UseriD, QuestionId and ConductedById

以下是我想要的目标数据:

enter image description here

Response列和Response rating列与各行连接,Rating Avg列取平均值。我之前使用stuff函数完成了一个列连接。这可以使用填充函数来实现吗?

2 个答案:

答案 0 :(得分:4)

您可以执行以下操作。只需按这些列分组,并为连续列创建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

答案 1 :(得分:-1)

这很好用

STUFF( 
( 
   SELECT DISTINCT ',' + val_name 
          FROM   t_t43_value_set 
             INNER JOIN     t_t43_factory 
             ON             val_id = fac_country 
             INNER JOIN     t_t43_delivery delivery 
             ON   pvs_part_version_id = del_part_version_id 
             AND  pvs_supplier_id = del_supplier_id 
             AND  del_factory_id = fac_factory_id FOR xml path('')),1,1,'') AS 'Country'