Concatenating Values Based on ID: A Solution Using SQL
When working with data, the need to concatenate values based on shared IDs arises frequently. In this scenario, we encounter a table with a list of Response IDs and associated Labels. Our goal is to transform this data into a format where each row displays the Response ID and a comma-separated list of Labels.
To achieve this, we can leverage SQL's grouping and concatenation capabilities. We begin by declaring a temporary table called @T and populating it with the sample data. The query below outlines the steps involved:
select T1.Response_ID, stuff((select ','+T2.Label from @T as T2 where T1.Response_ID = T2.Response_ID for xml path(''), type).value('.', 'varchar(max)'), 1, 1, '') as Label from @T as T1 group by T1.Response_ID
By executing this query, we obtain the transformed data where each row represents a Response ID with the associated Labels concatenated and separated by commas. This solution provides an efficient way to aggregate and present data based on shared identifiers.
The above is the detailed content of How to Concatenate Labels Based on Response ID Using SQL?. For more information, please follow other related articles on the PHP Chinese website!