2016-09-25 21 views
0

我有一個數據透視表,顯示學生缺席,沒有執行中的問題和透視的結果,但如果沒有值,它顯示空值,我想顯示0不是null。我谷歌搜索,並找到了一些方法,我嘗試使用它們,但我不能做到這一點。誰能告訴我嗎? 這是我的數據透視表的代碼:如何在數據透視表輸出值中將NULL替換爲0

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);

回答

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); 
相關問題