如何使用列作为键来透视 SQL 中的列
How to use a column as a key to pivot columns in SQL
我正在尝试调整 table 并汇总一些子类别。但是,在聚合时,子类别没有正确连接。
例子Table
| category | categorySub |
|----------|-------------|
| cat-1 | sub-1 |
| cat-1 | sub-2 |
| cat-1 | sub-3 |
| cat-2 | sub-4 |
| cat-2 | sub-5 |
实际输出
| 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"] |
期望输出
| category | categorySub |
|----------|---------------------------|
| cat-1 | ["sub-1","sub-2","sub-3"] |
| cat-2 | ["sub-4","sub-5"] |
查询
select
[categoryMain] = [category],
[categorySub] = '["' + (select string_agg(categorySub, '","') from someTable where [categoryMain] = [category]) + '"]'
from someTable
group by [category]
如何引用 [category] 或其别名来减少字符串聚合?
正如 Martin 所建议的,我们可以像这样直接使用 string_agg
:
select
[categoryMain] = [category],
[categorySub] = '["' + (select string_agg(categorySub, '","') + '"]'
from someTable
group by [category]
您可以在 STRING_AGG
本身中使用它
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]
我正在尝试调整 table 并汇总一些子类别。但是,在聚合时,子类别没有正确连接。
例子Table
| category | categorySub |
|----------|-------------|
| cat-1 | sub-1 |
| cat-1 | sub-2 |
| cat-1 | sub-3 |
| cat-2 | sub-4 |
| cat-2 | sub-5 |
实际输出
| 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"] |
期望输出
| category | categorySub |
|----------|---------------------------|
| cat-1 | ["sub-1","sub-2","sub-3"] |
| cat-2 | ["sub-4","sub-5"] |
查询
select
[categoryMain] = [category],
[categorySub] = '["' + (select string_agg(categorySub, '","') from someTable where [categoryMain] = [category]) + '"]'
from someTable
group by [category]
如何引用 [category] 或其别名来减少字符串聚合?
正如 Martin 所建议的,我们可以像这样直接使用 string_agg
:
select
[categoryMain] = [category],
[categorySub] = '["' + (select string_agg(categorySub, '","') + '"]'
from someTable
group by [category]
您可以在 STRING_AGG
本身中使用它
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]