我有带有动态TabHeader的表,例如:
RecordNum | TabHeader | tabvalue
1 A data1
1 B data2
1 C data3
2 A Data4
2 B data5
2 c data6
3 A Data7
我想创建要实现的查询表:
recordNum | A | B | C |
1 data1 data2 data3
2 data4 data5 data6
3 data7
我尝试使用数据透视,但没有运气, 拜托任何人都可以帮助我 查询:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(tablecoloumnmap)
from temptes
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT recordnum ' + @cols + ' from
(
select *
from temptes
) x
pivot
(
max(tablevalue)
for tablecoloumnmap in (' + @cols + ')
) p '
execute(@query)
答案 0 :(得分:1)
您可以改为使用条件聚合:
select RecordNum,
max(case when tabheader = 'A' then tabvalue end) as A,
max(case when tabheader = 'B' then tabvalue end) as B,
max(case when tabheader = 'C' then tabvalue end) as C
from table t
group by RecordNum;
编辑::这是Pivot的动态版本:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(TabHeader)
FROM temptes
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)') , 1, 1, ''
)
SET @query = N'select *
from temptes x pivot
( max(tabvalue)
for TabHeader in (' + @cols + ')
) p '
EXECUTE (@query)
答案 1 :(得分:0)
您好,对您现有的sql脚本进行了一些更正,它将提供您期望的确切结果
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(TabHeader)
from temptes
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT recordnum ,' + @cols + ' from
(
select *
from temptes
) x
pivot
(
max(tabvalue)
for TabHeader in (' + @cols + ')
) p '
PRINT @query
execute(@query)
结果
Recordnum A B C
----------------------------------
1 data1 data2 data3
2 Data4 data5 data6
3 Data7 NULL NULL