[英]How can i use stuff function for multiple columns in SQL server?
我需要连接具有相同 Id 的两行的两个值并为其他列求平均值。 这是我的示例表:
现在我的要求是我需要连接Response
列,连接Response Rating
列并平均Rating Avg
列,如果它具有相同的ParticipantId, UseriD, QuestionId and ConductedById
。
这是我想要的目标数据:
这里Response
列和Response rating
列与各自的行连接, Rating Avg
列取平均值。 我以前使用stuff
函数完成了一列连接。 这可以使用东西功能来实现吗?
您可以执行以下操作。 只需按这些列分组并为连接列进行 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
这完美地工作
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.