-1
As of 2017 version of SQL Server
you can use the function STRING_AGG
that allows grouping and concatenating results:
SELECT pptm.product_id,
STRING_AGG(pptm.producttag_id, ', ') AS producttag_id
FROM Product_ProductTag_Mapping pptm
GROUP BY pptm.product_id;
For previous versions you can create a function to concatenate the results by product_id
:
CREATE FUNCTION fn_tgs(@product_id INT)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @text NVARCHAR(MAX) = '';
SELECT @text = ISNULL(@text + ',', '') + pptm.producttag_id
FROM Product_ProductTag_Mapping pptm
WHERE pptm.product_id = @product_id;
RETURN @text;
END;
And use as follows:
SELECT pptm.product_id,
fn_tgs(pptm.producttag_id) AS producttag_id
FROM Product_ProductTag_Mapping pptm
GROUP BY pptm.product_id;
Concatenate the values of the string expressions and place the separator values between them. Separator is not added at the end of the string.
look for pivot table, here are some answers on that
– Ricardo Pontual
Obrigado Ricardo!
– Fernando Adão
@Ricardopunctual in fact the
PIVOT
only solve if he wanted a column per result, but in case he just wants to concatenate the results. For this he should use something like theSTRING_AGG
.– Sorack
But @Sorack works by grouping and concatenating? That’s interesting, I’ll see ;)
– Ricardo Pontual
@Ricardopunctual yes, but only from the 2017 version of
SQL Server
– Sorack