我有下表:
CREATE TABLE pvt
(
cola varchar(10),
colb varchar(10)
)
insert into pvt values('','2');
insert into pvt values('1','3');
insert into pvt values('9','4');
insert into pvt values('8','5');
数据透视表查询:
DECLARE @StuffColumn varchar(max)
DECLARE @sql varchar(max)
SELECT @StuffColumn = STUFF((SELECT ','+QUOTENAME(cola)
FROM pvt
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
PRINT(@StuffColumn)
SET @SQL = ' select colb,'+ @StuffColumn +'
from
(
select cola,colb
from pvt
)x
pivot
(
count(cola)
for cola in( '+@StuffColumn +')
)p'
PRINT(@SQL)
EXEC(@SQL)
错误:
Msg 1038, Level 15, State 4, Line 1
An object or column name is missing or empty. For SELECT INTO statements,
verify each column has a name. For other statements, look for empty alias
names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.
预期结果:
colb 1 9 8
-------------------
2 1 0 0 0
3 0 1 0 0
4 0 0 1 0
5 0 0 0 1
答案 0 :(得分:2)
这个怎么样:
DECLARE @StuffColumn varchar(max)
DECLARE @sql varchar(max)
SELECT @StuffColumn = STUFF((SELECT ','+QUOTENAME(case when cola = '' then 'empty' else cola end)
FROM pvt
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
PRINT(@StuffColumn)
SET @SQL = ' select colb,'+ @StuffColumn +'
from
(
select case when cola = '''' then ''empty'' else cola end as cola,colb
from pvt
)x
pivot
(
count(cola)
for cola in( '+@StuffColumn +')
)p'
PRINT(@SQL)
EXEC(@SQL)
您需要为枢轴列命名。
多个空列+动态数据透视的解决方案:
DECLARE @StuffColumn varchar(max)
DECLARE @sql varchar(max)
SELECT @StuffColumn = STUFF((SELECT ','+QUOTENAME(case when cola = '' then Cast(ROW_NUMBER() over (order by colb) as varchar (6)) + 'empty' else cola end)
FROM pvt
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
PRINT(@StuffColumn)
SET @SQL = ' select colb,'+ @StuffColumn +'
from
(
select case when cola = '''' then Cast(ROW_NUMBER() over (order by colb) as varchar (6)) +''empty'' else cola end cola,colb
from pvt
)x
pivot
(
count(cola)
for cola in( '+@StuffColumn +')
)p'
PRINT(@SQL)
EXEC(@SQL)