2

I am trying to pivot a table and aggregate some sub-categories. However, when aggregating, the sub-categories aren't joining properly.

Example Table

| category | categorySub |
|----------|-------------|
| cat-1    | sub-1       |
| cat-1    | sub-2       |
| cat-1    | sub-3       |
| cat-2    | sub-4       |
| cat-2    | sub-5       |

Actual Output

| category | categorySub                               |
|----------|-------------------------------------------|
| cat-1    | ["sub-1","sub-2","sub-3","sub-4","sub-5"] |
| cat-2    | ["sub-1","sub-2","sub-3","sub-4","sub-5"] |

Desired Output

| category | categorySub               |
|----------|---------------------------|
| cat-1    | ["sub-1","sub-2","sub-3"] |
| cat-2    | ["sub-4","sub-5"]         |

Query

select 
[categoryMain] = [category],
[categorySub] = '["' + (select string_agg(categorySub, '","') from someTable where [categoryMain] = [category]) + '"]'
from someTable
group by [category]

How can I reference [category] or its alias to pare down the string aggregation?

Matthew
  • 1,461
  • 3
  • 23
  • 49

2 Answers2

1

You can use that in STRING_AGG itself

DECLARE @T Table(
cat Varchar(max),
SUB varchar(max))

Insert into @T Values ('cat-1','sub-1')
Insert into @T Values ('cat-1','sub-2')
Insert into @T Values ('cat-1','sub-3')
Insert into @T Values ('cat-2','sub-4')
Insert into @T Values ('cat-2','sub-5')

SELECT CAT AS CATEGORYMAIN, '["' + STRING_AGG(SUB, '","')+ '"]' AS SUB 
FROM @T GROUP BY [CAT]
Thiyagu
  • 1,260
  • 1
  • 5
  • 14
0

As Martin suggested, we can use string_agg directly like:

select 
[categoryMain] = [category],
[categorySub] = '["' + (select string_agg(categorySub, '","') + '"]'
from someTable
group by [category]
Matthew
  • 1,461
  • 3
  • 23
  • 49