-1

I wish to convert redundant row values into a comma separated string to build a JSON. Here in my example the columns I need to convert to comma separated string is attrValueId, attrValue and name.

Please use the snippet to build the schema

CREATE TABLE t
    ([attrId] int, [displayPosition] int, 
     [attrValueId] int, [attrValue] varchar(30),
    name varchar(30), attrName varchar(30),attrType varchar(30),
    isRequired bit);

INSERT INTO t    VALUES
    (1,2,1,'123',NULL,'testattribute','dropdown',0);
INSERT INTO t  VALUES
    (1,2,2,'1234',NULL,'testattribute','dropdown',0);
INSERT INTO t    VALUES
    (3,1,6,'miuu2',NULL,'mult','multi-select',1);
INSERT INTO t VALUES
    (3,1,7,'miuu3396',NULL,'mult','multi-select',1);

The table data is like

attrId  displayPosition attrValueId attrValue   name    attrName        attrType        isRequired
1       2               1           123         NULL    testattribute   dropdown        0
1       2               2           1234        NULL    testattribute   dropdown        0
3       1               6           miuu2       NULL    mult            multi-select    1
3       1               7           miuu3396    NULL    mult            multi-select    1

My required result is

  attrId    displayPosition attrValueId attrValue      name      attrName      attrType     isRequired
  1         2               1,2         1234,1234      NULL,NULL testattribute  dropdown     0
  3         1               6,7         miuu2,miuu3396 NULL,NULL mult           multi-select 1

My ultimate aim is to construct a JSON string in the format

    [
{"attrId":"1","displayPosition":"2","attrValueId":["1,2"],"attrValue":["1234,1234"],"name":["null","null"],"attrName":"testattribute","attrType":"dropdown","isRequired":"0"}
,
{second row goes here}]
Dale K
  • 25,246
  • 15
  • 42
  • 71
Surensiveaya
  • 297
  • 1
  • 12

1 Answers1

0

Try using STRING_AGG() by doing GROUP BY over attrId & displayPosition

I have one sample for you.

SELECT 
    [attrId]
    ,[displayPosition]
    ,STRING_AGG([attrValueId],',') [attrValueId] 
    ,STRING_AGG(name,',') name 
    ,STRING_AGG([attrValue],',') [attrValue]   
    ,STRING_AGG(attrType,',') attrType, isRequired
 FROM t group by [attrId],[displayPosition],isRequired

I have assumed that [attrId],[displayPosition],isRequired uniquely represent one row.

For Old SQL Server versions, try STUFF() Check the following threads: Group By and STUFF combined result in sql server

How to use GROUP BY to concatenate strings in SQL Server?

mehtasuraj09
  • 139
  • 12