1
我有下表,其中包含一些记录。在动态数据透视表中多次指定的列
例:
表:记录 ffortest
create table ffortest
(
col1 int,
col2 int
)
插入:
insert into ffortest values(1,2);
insert into ffortest values(3,4);
insert into ffortest values(5,6);
insert into ffortest values(7,8);
insert into ffortest values(9,2);
insert into ffortest values(1,2);
透视表查询:
DECLARE @StuffColumn varchar(max)
DECLARE @sql varchar(max)
SELECT @StuffColumn = STUFF((SELECT ','+QUOTENAME(col1)
FROM ffortest
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
PRINT(@StuffColumn)
SET @SQL = ' select col2,'+ @StuffColumn +'
from
(
select col1,col2
from ffortest
)x
pivot
(
count(col1)
for col1 in('[email protected] +')
)p'
PRINT(@SQL)
EXEC(@SQL)
错误:列 '1' 指定的多个时间在第
预期的结果是:
col2 1 9 3 5 7
-------------------
2 2 1 0 0 0
4 0 0 1 0 0
6 0 0 0 1 0
8 0 0 0 0 1