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}]