我需要一个带有分组依据和动态列名的枢轴?
我有一个查询,它给了我这样的数据:
|
姓名
|
类型
|
类型2
|
价值观
|
|
名称1
|
短
|
A.
|
some_string
|
|
名称1
|
短
|
B
|
some_string
|
|
名称1
|
长
|
A.
|
some_string
|
|
名称1
|
长
|
B
|
some_string
|
|
名称2
|
短
|
A.
|
some_string
|
|
名称2
|
短
|
B
|
some_string
|
|
名称2
|
长
|
A.
|
some_string
|
|
名称2
|
长
|
B
|
some_string
|
对于这个问题,我们可以假设数据在#Test中
现在,我需要一个这样的结构:
|
姓名
|
短-A
|
短-B
|
短-C
|
龙A
|
长B
|
长-C
|
|
名称1
|
some_string
|
some_string
|
无效的
|
some_string
|
some_string
|
无效的
|
|
名称2
|
some_string
|
some_string
|
无效的
|
some_string
|
some_string
|
无效的
|
我的示例代码:
create table Test
(
name varchar(20) not null
, Type1 varchar(20) not null
, Type2 varchar(20) not null
, Value varchar(50) null
)
insert into dbo.Test (name, Type1, Type2, Value) values ('name1', 'Short', 'A', 'loreipsum1')
insert into dbo.Test (name, Type1, Type2, Value) values ('name1', 'Short', 'B', 'loreipsum2')
insert into dbo.Test (name, Type1, Type2, Value) values ('name1', 'Long', 'A', 'loreipsum3')
insert into dbo.Test (name, Type1, Type2, Value) values ('name1', 'Long', 'B', 'loreipsum4')
insert into dbo.Test (name, Type1, Type2, Value) values ('name2', 'Short', 'A', 'loreipsum5')
insert into dbo.Test (name, Type1, Type2, Value) values ('name2', 'Short', 'B', 'loreipsum6')
insert into dbo.Test (name, Type1, Type2, Value) values ('name2', 'Long', 'A', 'loreipsum7')
insert into dbo.Test (name, Type1, Type2, Value) values ('name2', 'Long', 'B', 'loreipsum8')
select * into #Data from dbo.Test;
select x.*
into #Typ1
from (select 'Short' Typ
union
select 'Long' Typ
) x;
select x.*
into #Typ2
from (select 'A' Typ
union
select 'B' Typ
union
select 'C' Typ
) x;
declare @PivotQuery nvarchar(max)
, @Typ1 nvarchar(max)
, @Typ2 nvarchar(max);
select @Typ1 = string_agg (QUOTENAME (Typ), ', ') from #Typ1;
select @Typ2 = string_agg (QUOTENAME (Typ), ', ') from #Typ2;
set @PivotQuery = 'select *
into #X
from
(
select name, type1, type2, value from #Data
) as SRC
pivot
(
max(Value)
for Type1 in (' + @Typ1 + ')
) as PVT1;
select * from #X;';
EXECUTE sp_executesql @PivotQuery;
类型1的列表是恒定的(总是短和长),但类型2的列表会发生变化(有时是A-C,有时是A-F等)
我以Type1为中心,但不知道接下来会发生什么