I have a requirement for concatenating two values of two rows having same Id's and averaging for other column. Here is the sample table I have:
Now my requirement is I need to concatenate the Response
column, concatenate Response Rating
column and average the Rating Avg
column if it has same ParticipantId, UseriD, QuestionId and ConductedById
.
Here is the target data what I wanted:
Here Response
column and Response rating
column is concatenated with respective rows and Rating Avg
column is taken the average. I have done one column concatenation previously using stuff
function. Can this be achieved using stuff function?
To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.
The STUFF function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.
But the WHERE.. IN clause allows only 1 column.
You can do the following. Just group by those columns and make 2 subselects for concatenated columns:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With