我有一个显示学生缺席的数据透视表,执行中没有问题和数据透视的结果但是如果没有值则显示null,我想显示0而不是null。我用谷歌搜索并找到了一些尝试使用它们的方法,但我不能这样做。有人能告诉我吗? 这是我的数据透视表代码:
create proc [dbo].[get_st_abs_by_stage]
@Stage_ID smallint
as
CREATE TABLE #SummaryTable
(
SName nvarchar(50),
CName nvarchar(50),
Stage_ID SmallInt,
Sum_Abs SmallInt
)
delete from #SummaryTable
INSERT INTO #SummaryTable(SName, CName, Stage_ID, Sum_Abs)
SELECT Student_tbl.SName,Courses_tbl.CName,Stages_tbl.Stage_ID,Sum_Abs from Absence_Summary_tbl
inner join Student_tbl on Student_tbl.S_ID = Absence_Summary_tbl.S_ID
inner join Stages_tbl on Stages_tbl.Stage_ID = Student_tbl.Stage_ID
inner join Courses_tbl on Courses_tbl.C_ID = Absence_Summary_tbl.C_ID
where Stages_tbl.Stage_ID = @Stage_ID;
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(CName)
from #SummaryTable
where Stage_ID = @Stage_ID
group by CName
order by CName
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
set @query = 'SELECT SName,' + @cols + ' from
(
select SName, CName, Sum_Abs
from #SummaryTable
) x
pivot
(
sum(Sum_Abs)
for CName in (' + @cols + ')
) p '
execute(@query);
答案 0 :(得分:1)
您可以使用isnull为cols生成另一个变量。像这样的东西
select @cols = STUFF((SELECT ',' + QUOTENAME(CName)
from #SummaryTable
where Stage_ID = @Stage_ID
group by CName
order by CName
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
select @isnull_cols = STUFF((SELECT ', isnull(' + QUOTENAME(CName) + ', 0) as ' + QUOTENAME(CName)
from #SummaryTable
where Stage_ID = @Stage_ID
group by CName
order by CName
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
set @query = 'SELECT SName,' + @isnull_cols + ' from
(
select SName, CName, Sum_Abs
from #SummaryTable
) x
pivot
(
sum(Sum_Abs)
for CName in (' + @cols + ')
) p '
execute(@query);