简体   繁体   中英

How to use a column as a key to pivot columns in SQL

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?

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]

As Martin suggested, we can use string_agg directly like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM