J'ai une exigence pour concaténer deux valeurs de deux rangées ayant les mêmes Id et faisant la moyenne pour l'autre colonne. Voici l'exemple de tableau que j'ai:
Maintenant, mon exigence est que je dois concaténer la colonne Response
, concaténer la colonne Response Rating
et faire la moyenne de la colonne Rating Avg
si elle a les mêmes ParticipantId, UseriD, QuestionId and ConductedById
.
Voici datatables cibles que je voulais:
Ici, la colonne Response
et la colonne Response rating
sont concaténées avec les lignes respectives et la colonne Rating Avg
est prise en moyenne. J'ai déjà fait une concaténation de colonne en utilisant la fonction stuff
. Cela peut-il être réalisé en utilisant la fonction stuff?
Vous pouvez faire ce qui suit. Groupez simplement par ces colonnes et faites 2 sous-sélections pour les colonnes concaténées:
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